[英]Java Regex get all numbers
I need to retrieve all numbers from a String, example :我需要从字符串中检索所有数字,例如:
"a: 1 | b=2 ; c=3.2 / d=4,2"
I want get this result :我想得到这个结果:
So, i don't know how to say that in Regex on Java.所以,我不知道在 Java 上的正则表达式中怎么说。
Actually, i have this :实际上,我有这个:
(?<=\D)(?=\d)|(?<=\d)(?=\D)
He split letter and number (but the double value is not respected), and the result is :他拆分了字母和数字(但不尊重double值),结果是:
Can you help me ?你能帮助我吗 ?
Thanks :D感谢:D
You might use a capturing group with a character class :您可以使用带有字符类的捕获组:
[a-z][:=]\h*(\d+(?:[.,]\d+)?)
Explanation解释
[az]
Word boundary, match a char az [az]
词边界,匹配一个字符 az[:=]
Match either :
or =
[:=]
匹配:
或=
\\h*
Match 0+ horizontal whitespace chars \\h*
匹配 0+ 个水平空白字符(
Capture group 1 (
捕获组 1
\\d+(?:[.,]\\d+)?
Match 1+ digits with an optional decimal part with either .
.
or ,
,
)
Close group )
关闭群组Regex demo |正则表达式演示| Java demo
Java 演示
For example例如
String regex = "[a-z][:=]\\h*(\\d+(?:[.,]\\d+)?)";
String string = "a: 1 | b=2 ; c=3.2 / d=4,2";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
System.out.println(matcher.group(1));
}
Output输出
1
2
3.2
4,2
You can do it as follows:你可以这样做:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) throws InterruptedException {
// Test
String s = "a: 1 | b=2 ; c=3.2 / d=4,2";
showNumbers(s);
}
static void showNumbers(String s) {
Pattern regex = Pattern.compile("\\d[\\d,.]*");
Matcher matcher = regex.matcher(s);
while (matcher.find()) {
System.out.println(matcher.group());
}
}
}
Output:输出:
1
2
3.2
4,2
You may jsut need a regex like (\\d(?:[.,]\\d)?)
that你可能需要一个像
(\\d(?:[.,]\\d)?)
这样的正则表达式
The multi-digit version is (\\d+(?:[.,]\\d+)?)
多位数版本是
(\\d+(?:[.,]\\d+)?)
String value = "a: 1 | b=2 ; c=3.2 / d=4,2";
Pattern p = Pattern.compile("(\\d(?:[.,]\\d)?)");
Matcher m = p.matcher(value);
while (m.find()) {
System.out.println(m.group());
}
// 1
// 2
// 3.2
// 4,2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.