0

I have a string

String text="abc19xyz87nag";

I need to get only the numbers out of it, so I applied "\\D+" regex as below,

String text="abc19xyz87nag";
String[] tks=text.split("\\D+");

But I see a empty token in the beginning of the array
enter image description here

How ever I have found out two other solutions anyway as below

Using scanner

Scanner sc = new Scanner(text).useDelimiter("\\D+");
        while(sc.hasNext()) {
            System.out.println(sc.nextInt());
        }

Using Pattern and Matcher

Matcher m = Pattern.compile("\\d+").matcher(text);
        while (m.find()) { 
             System.out.println(m.group());
            }

So Why string split is leaving empty token at the beginning?
Do I need to change the regex to avoid it?
Any help is appreciated

gowtham
  • 977
  • 7
  • 15

4 Answers4

1

It is a design decision to not discard empty strings at the beginning. The rationale is that split() is often used with data like

item1, item2, item3

(here the delimitter is ',') and you want to keep the non-null items at their positions.

Now, suppose you parse lines with 3 items like above, where the first and the last are optional. If split would discard both leading and trailing empty strings, and you get 2 elements back, you couldn't decide whther the input was:

, item2, item3

or

item1, item2

By only discarding empty strings at the end, you know that every non-empty string is at its correct position.

Ingo
  • 36,037
  • 5
  • 53
  • 100
0

Your Regex should be like

[^\d]

Hope it helps

Mayank Pathak
  • 3,621
  • 5
  • 39
  • 67
0
String s = "smt-ing we want to split");
StringTokenizer st = new StringTokenizer();
while(st.hasMoreTokens()){
System.out.println(st.nextToken());
}
Ruben JG
  • 97
  • 7
0

You can do some validation to remove that empty String.

    String text="abc19xyz87nag";
    String[] tks=text.split("\\D+");
    List<String> numList=new ArrayList<>();
    for(String i:tks){
       if(!"".equals(i)){
           numList.add(i);
       }
    }
Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115