我需要从字符串中检索所有数字,例如:
"a: 1 | b=2 ; c=3.2 / d=4,2"
我想得到这个结果:
- 1
- 2
- 3.2
- 4,2
所以,我不知道在 Java 上的正则表达式中怎么说。
实际上,我有这个:
(?<=\D)(?=\d)|(?<=\d)(?=\D)
他将字母和数字分开(但不考虑 double 值),结果是:
- 1
- 2
- 3
- 2(问题)
- 4
- 2(问题)
你能帮我吗?
谢谢:D
最佳答案
您可以使用带有 character class 的捕获组:
[a-z][:=]\h*(\d+(?:[.,]\d+)?)
说明
[a-z]
单词边界,匹配字符 a-z[:=]
匹配:
或=
\h*
匹配 0+ 水平空白字符(
捕获组 1\d+(?:[.,]\d+)?
使用.
或,
匹配带有可选小数部分的 1 个以上数字>
)
关闭群组
例如
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));
}
输出
1
2
3.2
4,2
关于Java正则表达式获取所有数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60496631/