Java. Find all numbers in the String.
Use RepalceAll
String str = "qwerty1qwerty2";
str = str.replaceAll("[^0-9]+", " ");
System.out.println(Arrays.asList(str.trim().split(" ")));
Output:
[1, 2]
[EDIT]
If you want to include
-
a.e minus, add -?
:String str = "qwerty-1qwerty-2 455 f0gfg 4";
str = str.replaceAll("[^-?0-9]+", " ");
System.out.println(Arrays.asList(str.trim().split(" ")));
Output:
[-1, -2, 455, 0, 4]Get number in indext:
int k = Integer.parseInt(Arrays.asList(str.trim().split(" ")).get(0));
OR
Pattern p = Pattern.compile("-?\\d+");
Matcher m = p.matcher("There are more than -2 and less than 12 numbers here");
while (m.find()) {
System.out.println(m.group());
}
... prints -2 and 12.
No comments: