【发布时间】:2017-11-23 07:58:03
【问题描述】:
我有字符串:Entry, x: 0.0 y: -0.9980941 Entry, x: 1.0 y: -0.9686125 Entry, x: 2.0 y: 0.9044667
如何通过正则表达式获取所有浮点值:0.0, -0.9980941, 1.0, -0.9686125, 2.0, 0.9044667
【问题讨论】:
我有字符串:Entry, x: 0.0 y: -0.9980941 Entry, x: 1.0 y: -0.9686125 Entry, x: 2.0 y: 0.9044667
如何通过正则表达式获取所有浮点值:0.0, -0.9980941, 1.0, -0.9686125, 2.0, 0.9044667
【问题讨论】:
以下是来自https://www.regular-expressions.info/floatingpoint.html的正则表达式
[-+]?[0-9]*.?[0-9]+
【讨论】:
您可以使用 java.util.regex 包来做到这一点。
正则表达式 \d 匹配数字 & 等价于 [0..9]。 \d* 要求匹配前面表达式的 0 次或多次出现。 “。?”匹配 0 或 1 次出现的点。 \d+ 匹配前一个 \d 的 1 个或多个表达式。因此,regEx 一起在字符串中搜索 [0..9].[0..9] 模式。
查看java_regular_expressions 了解 *, 之间的区别。 ,?和 + 在正则表达式中。
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String str = "Entry, x: 0.0 y: -0.9980941 Entry, x: 1.0 y: -0.9686125 Entry, x: 2.0 y: 0.9044667";
String regEx = "\\d*\\.?\\d+";
Pattern patternObject = Pattern.compile(regEx);
Matcher matcher = patternObject.matcher(str);
while (matcher.find()) {
System.out.println(matcher.group());
}
}
}
【讨论】:
请注意@Ashish Mathew 建议的[-+]?[0-9]*.?[0-9]+ 模式对我不起作用,因为. 需要转义。
另外,我建议您阅读他发布的链接,以便您找到最终的工作解决方案及其构建方式以及解释。
这是我基于它的工作代码:
public static void main(String[] args) {
String s = " Entry, x: 0.0 y: -0.9980941 Entry, x: 1.0 y: -0.9686125 Entry, x: 2.0 y: 0.9044667";
List<String> allMatches = new ArrayList<>();
Matcher m = Pattern.compile("[-+]?[0-9]+\\.?[0-9]*").matcher(s);
while (m.find()) {
allMatches.add(m.group());
}
// [0.0, -0.9980941, 1.0, -0.9686125, 2.0, 0.9044667]
System.out.println(allMatches);
}
【讨论】: