[英]How to extract only number from a string in java?
Supposedly I have a string that contains: hello 14:12
. 据说我有一个字符串,其中包含:
hello 14:12
。
Now I want to extract only the number and have two separate value in two variable like this: first_num value should be int ie first_num = 14 and the second variable should store the number after the colon ( :
) ie second_num = 12. 现在我想仅提取的数量和具有在像这样的两个可变两个单独的值:FIRST_NUM值应是int即FIRST_NUM = 14和第二可变应冒号后的数目存储(
:
),即second_num = 12。
ReplaceAll is the best solution ReplaceAll是最好的解决方案
String str = "hello 14:12";
str = str.replaceAll("[^0-9]+", " ");
System.out.println(Arrays.asList(str.trim().split(" ")));
In this way you can attain only numbers in the array. 这样,您只能在数组中获得数字。
You can use Regex to solve the problem 您可以使用正则表达式解决问题
public static List<Integer> extractNumbers(String s){
List<Integer> numbers = new ArrayList<Integer>();
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(s);
while(m.find()){
numbers.add(Integer.parseInt(m.group()));
}
return numbers;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.