gpt4 book ai didi

java - 拒绝特定单词之前的价格,正则表达式java

转载 作者:行者123 更新时间:2023-12-01 20:18:03 24 4
gpt4 key购买 nike

我有:“价格是 1 000 美元,另外 34 000 美元,00 欧元。您必须支付 1400 欧元,还必须支付额外的 2000 美元”。我想要的是?我想要价格,但如果价格之前有“付费”或“额外付费”一词,那么我必须拒绝这个价格。我有给我价格的正则表达式,所以它很棒,但我认为我需要另一个?或者修改正则表达式,如果价格之前是特定单词,则拒绝某些价格。我的示例的输出应该是:1000,34000我的代码:

String regex = "(([0-9]+[\\s,.]*)+)(\\$|EUR)";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
price = matcher.group();
if (price.contains(",")) {
price = price.substring(0, price.indexOf(","));
}
price = price.replaceAll("\\s", "").replaceAll("[^0-9]+", "");
if (price.contains(",")) {
price = price.replaceAll("\\,", "");
} else {
price = price.replaceAll("\\.", "");
}

它给了我:

1000,34000,1400,2000

但我只想要:1000,34000 我必须拒绝这些“付费”和“额外付费”后面的价格。编辑: ”。”是这样的价格 1 000. 00

最佳答案

我知道您有一些字符串,其中小数点分隔符是逗号,点是数字分组符号。

您可以匹配paypay extra作为可选捕获组的单词 (\\bpay(?:\\s+extra)?\\s*)?并检查该组是否匹配。如果是,则应丢弃该匹配,否则,抓取该号码并删除 ,及其后面的数字。然后,删除所有非数字符号。

请参阅Java demo :

String text = "The price is 1 000$ another pice 34 000 , 00 EUR. You have to pay 1400 EUR, and you have to pay extra 2000$";
String regex = "(\\bpay(?:\\s+extra)?\\s*)?(\\d[\\d\\s,.]*)(?:\\$|EUR)";
Pattern pattern = Pattern.compile(regex);
Matcher m = pattern.matcher(text);
List<String> res = new ArrayList<>();
while (m.find()) {
if (m.group(1) == null) {
res.add(m.group(2).replaceAll(",\\s*\\d+|\\D", ""));
}
}
System.out.println(res);
// => [1000, 34000]

图案详细信息:

  • (\\bpay(?:\\s+extra)?\\s*)? - 匹配整个单词的可选捕获组 paypay extra (其间有 1+ 个空格),然后是 0+ 个空格(当组不匹配时, matcher.group(1)null)
  • (\\d[\\d\\s,.]*) - 第 2 组:一个数字,然后是 0+ 个数字、空格、,或/和.符号
  • (?:\\$|EUR) - 匹配 $ 的非捕获组符号或EUR子字符串。

,\\s*\\d+|\\D模式匹配, 、0+ 空格和 1+ 数字或任何非数字符号。

注意:如果您可以同时拥有两者 .,作为小数分隔符,在最后一个正则表达式中,替换 ,[,.] 。请参阅this Java demo .

关于java - 拒绝特定单词之前的价格,正则表达式java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45415457/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com