-8

I am trying to extract the numbers from the following string:

(1234-5869)|990-9797

I want all the numbers present in that string like

1234
5869
990
9797 
James Whiteley
  • 3,363
  • 1
  • 19
  • 46
  • 2
    If you say "I'm trying", you must have some code that does not work for you. Please add it to the question and explain what is wrong with it. – Wiktor Stribiżew May 15 '18 at 09:21
  • 1
    `Integer[] result = Arrays.stream("1234-5869)|990-9797".split("\\D")).filter(s->!s.isEmpty()).map(Integer::valueOf).toArray(Integer[]::new);` – Youcef LAIDANI May 15 '18 at 09:59

3 Answers3

0

in your case you don't need any regex. You need to split your string. look at this topic : How to split a string in Java

or if you want to make it without split you can replace all spetial caractere by a a blank space and then use a stringTokenizer like this :

String str = "(1234-5869)|990-9797";
str = str.replaceAll("\\D", " ")); // " 1234 5869  990 9797"

StringTokenizer st = new StringTokenizer(str);
while (st.hasMoreTokens()) {
     System.out.println(st.nextToken());
}

your answer will appear with the presentation you want

charles Lgn
  • 500
  • 2
  • 7
  • 28
-1
  • result==> String

    String string="(1234-5869)|990-9797";
    String onlyNumber= string.replaceAll("[^0-9]", "");
    System.out.println("result==>"onlyNumber);
    
  • result ==> array

    String string="(1234-5869)|990-9797";
    String normalizedString= string.replaceAll("[^0-9]", ",");
    System.out.println(normalizedString);
    StringTokenizer st = new StringTokenizer(normalizedString, ",");
    List<String> tabNumber= new ArrayList<String>();
    while (st.hasMoreElements()) {
        tabNumber.add((String) st.nextElement());
    }
    
khelwood
  • 55,782
  • 14
  • 81
  • 108
Jsk1986
  • 9
  • 4
-1

Use replaceAll.

String str = "(1234-5869)|990-9797";

System.out.println(str.replaceAll("\\D", " ")); // " 1234 5869  990 9797"

To get them into an array:

String[] arr = str.split("\\D");

System.out.println(Arrays.toString(arr)); // [, 1234, 5869, , 990, 9797]

You can then make them into a string with a loop and a StringBuilder or something similar, and trim off any empty values.

James Whiteley
  • 3,363
  • 1
  • 19
  • 46