There is a string, it contains numbers, say, a password - 450. How to get this number? The string may contain Russian text.
- That is, the line is not only one number, but something else? - angry
|
4 answers
If you know the structure of the string, you can use regular expressions .
/(\d+)/
=) - Sh4dow
|
import java.util.regex.*; Pattern pat=Pattern.compile("[-]?[0-9]+(.[0-9]+)?"); Matcher matcher=pat.matcher("45.5saf -fg123 -18+"); while (matcher.find()) { System.out.println(matcher.group()); };
So you can get all the numbers from the string.The result of this example is 45.5; 123; -18.
- @ReinRaus, yes, your code is better. - angry
- oneRegular expression is not correct) for example
44..1
- timka_s - Thanks, corrected. - ReinRaus
|
This code will find all the numbers in the string:
Pattern pattern = Pattern.compile("\\d+"); String word = "test123test444test"; // мой пример строки Matcher matcher = pattern.matcher(word); int start = 0; while (matcher.find(start)) { String value = word.substring(matcher.start(), matcher.end()); int result = Integer.parseInt(value); System.out.println(result); start = matcher.end(); }
|
String s1 ="пароль - 450"; String s2 = s1.split("\\\D+"); //s2 - символьный массив всех числовых вхождений.
The question is old, but search engines display it almost the first. You never know who will come in handy.
|