我需要在给定的文本行中提取价格信息。到目前为止,我在java中成功地使用了下面的regex (\\d{1,3}(,\\d{3})*(\\.\\d+)?)和price will be 90,500 USD这样的行。
但是,现在,在价格开始(eg: for order number 12345 the price will be 100,500 USD)之前,我也有了另一个号码的行。在这种情况下,我的价格提取失败。例如,上面给出的结果是123。
我可以有一个regex/另一种方法只提取价格信息,而不管是否存在其他数字?(无论小数点与否,价格总是以千为单位)
下面是我现在使用的用于这项工作的完整代码:
private String getPrice(String fileText) {
String lines[] = fileText.split(System.lineSeparator());
for (String line : lines) {
Pattern p = Pattern.compile("(\\d{1,3}(,\\d{3})*(\\.\\d+))");
Matcher m = p.matcher(line);
if (m.find()) {
return m.group(0);
}
p = Pattern.compile("(\\d{1,3}(,\\d{3})*(\\.\\d+)?)");
m = p.matcher(line);
if (m.find()) {
return m.group(0);
}
}
return "";
}我希望这场比赛是在文字级别。(eg: 123 of 12345 should not match.)我的单词分隔符仅为space。123-456被认为是一个单词。所以123456,123-456,123,456,123,456.56,A123456只有123,456,123,456.56应该匹配。问题是我当前的代码提取了123 of 123456,123-456和A123456
发布于 2019-05-13 08:35:40
您的正则表达式与任何上下文中的数字匹配,小数部分是必需的。
我建议:
使用
Pattern p = Pattern.compile("\\b\\d{1,3}(?:,\\d{3})*(?:\\.\\d+)?\\b");见regex演示。
\b模式是字边界,(?:...)?在(?:\\.\\d+)?中是一个非捕获组,重复一次或零次,也就是说是可选的。
https://stackoverflow.com/questions/56107665
复制相似问题