Reputation: 962
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?
Upvotes: 2
Views: 397
Reputation: 313
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
Upvotes: 1
Reputation: 174696
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.
Upvotes: 4
Reputation: 95948
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 \\
.
Upvotes: 9
Reputation: 16067
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.
Upvotes: 3
Reputation: 11890
You can use String.split()
:
String[] nbs = str.split("[^0-9]+");
This will split the String
on any group of non-numbers digits.
Upvotes: 4
Reputation: 43013
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
[124333, 9912111242, 12323335465645]
Upvotes: 1