2

I have a string which is of the form

String str = "124333 is the otp of candidate number 9912111242. 
         Please refer txn id 12323335465645 while referring blah blah.";

I need 124333, 9912111242 and 12323335465645 in a string array. I have tried this with

while (Character.isDigit(sms.charAt(i))) 

I feel that running the above said method on every character is inefficient. Is there a way I can get a string array of all the numbers?

6 Answers 6

9

Use a regex (see Pattern and matcher):

Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(<your string here>);
while (m.find()) {
    //m.group() contains the digits you want
}

you can easily build ArrayList that contains each matched group you find.

Or, as other suggested, you can split on non-digits characters (\D):

"blabla 123 blabla 345".split("\\D+")

Note that \ has to be escaped in Java, hence the need of \\.

Sign up to request clarification or add additional context in comments.

Comments

4

You can use String.split():

String[] nbs = str.split("[^0-9]+");

This will split the String on any group of non-numbers digits.

1 Comment

@user1051505 \D is [^0-9] BTW, so [^0-9]+ is simply \D+ (and you need to escape the backslash so you end up with \\D+.
4

And this works perfectly for your input.

String str = "124333 is the otp of candidate number 9912111242. Please refer txn id 12323335465645 while referring blah blah.";
System.out.println(Arrays.toString(str.split("\\D+")));

Output:

[124333, 9912111242, 12323335465645]

\\D+ Matches one or more non-digit characters. Splitting the input according to one or more non-digit characters will give you the desired output.

Comments

3

Java 8 style:

long[] numbers = Pattern.compile("\\D+")
                        .splitAsStream(str)
                        .mapToLong(Long::parseLong)
                        .toArray();

Ah if you only need a String array, then you can just use String.split as the other answers suggests.

Comments

1

Alternatively, you can try this:

String str = "124333 is the otp of candidate number 9912111242. Please refer txn id 12323335465645 while referring blah blah.";

str = str.replaceAll("\\D+", ",");
    
System.out.println(Arrays.asList(str.split(",")));

\\D+ matches one or more non digits

Output

[124333, 9912111242, 12323335465645]

Comments

1

First thing comes into my mind is filter and split, then i realized that it can be done via

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

\D matches any non-digit character, + says that one or more of these are needed, and leading \ escapes the other \ since \D would be parsed as 'escape character D' which is invalid

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.