[英]Java Regex to extract a number from a String
I have the following String input.我有以下字符串输入。
String s = "I have 5000 bananas";
I am extracting the numeric value using a regex String regex = "\\b\\d+\\b"
.我正在使用正则表达式
String regex = "\\b\\d+\\b"
提取数值。 This Regex is good in the sense that it would exclude any numericalAlpha mix words like a4 bc3
.这个正则表达式很好,因为它会排除任何 numericAlpha 混合词,如
a4 bc3
。
The issue happens when the user will input Strings like当用户输入字符串时会出现问题
String s1 = "I have 2 345 bananas";
String s2 = "I have 2,345 bananas";
String s3 = "I have #2345 bananas";
String s4 = "I have 5654 6 bananas";
My program should output an empty string in the above cases as none are valid numbers in the input String.在上述情况下,我的程序应该 output 一个空字符串,因为输入字符串中没有一个是有效数字。
You want to use a capturing group and the String method replaceAll.您想使用捕获组和 String 方法 replaceAll。
...
String[] strs = new String[] {
"I have 5000 bananas",
"I have 2 345 bananas",
"I have 2,345 bananas",
"I have #2345 bananas",
"I have 5654 6 bananas"
};
for (String s : strs) {
if (s.matches("(\\d+)( \\D+)")) {
System.out.println(s.replaceAll("(\\d+)( \\D+)", "$1"));
}
else if (s.matches("(\\D+ )(\\d+)")) {
System.out.println(s.replaceAll("(\\D+ )(\\d+)", "$2"));
}
else if (s.matches("(\\D+ )(\\d+)( \\D+)")) {
System.out.println(s.replaceAll("(\\D+ )(\\d+)( \\D+)", "$2"));
}
else {
// Just for demonstration on "displaying" or
// if you need to return or assign an empty string
System.out.println("");
}
}
...
Running that for your provided test cases will yield: (I am using the string "No match" instead of an empty string just to demonstrate)为您提供的测试用例运行它会产生:(我使用字符串“No match”而不是空字符串来演示)
5000
No match
No match
No match
No match
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.