【问题标题】:Java - How to write a regex that includes disjunction of variables of a given setJava - 如何编写一个包含给定集合变量析取的正则表达式
【发布时间】:2013-08-01 15:15:54
【问题描述】:

我需要从给定的网页中检索数字后跟一些特定单位,例如 10 m、5 km...。这些特定单位是map<String, Integer> 的键。 keySet() 返回一个逗号分隔的列表,例如 ["m", "km"...]。有没有一种聪明的方法可以将集合作为变量的析取,比如["m"|"km"|...],这样我就可以在正则表达式中使用它,例如:

"(\\d+)"+ " " +"myMap.keySet()......"

【问题讨论】:

  • 不清楚您要做什么。你能给出一些相同的输入和输出吗?
  • 您还想在匹配中包含单位还是仅包含这些单位后面的数字?

标签: java regex map set information-retrieval


【解决方案1】:

怎么样

myMap.keySet().toString().replaceAll(",\\s*", "|").replaceAll("^\\[|\\]$", "")
//                       ^                         ^
//                       |                         +remove [ at start and ] at end
//                       +replace `,` and spaces after it with |

改为

myMap.keySet()

您的代码可能如下所示

String data = "1km is equal 1000 m, and 1  m is equal 100cm. 1 mango shouldnt be found";

Map<String, Integer> map = new HashMap<>();
map.put("m", 1);
map.put("km", 2);
map.put("cm", 3);

String regex = "\\d+\\s*("
        + map.keySet().toString()       //will create "[cm, m, km]"
            .replaceAll(",\\s*", "|")   //will change it to "[cm|m|km]"
            .replaceAll("^\\[|\\]$", "")//will change it to "cm|m|km"
        + ")\\b";                       
    // I added \\b - word boundary - to prevent matching `m` if it is at
    // start of some word like in 1 mango where it normally would match
    // (1 m)ango

Pattern p=Pattern.compile(regex);
Matcher m=p.matcher(data);
while(m.find()){
    System.out.println(m.group());
}

【讨论】:

    【解决方案2】:

    用管道加入集合: "(\\d+)\\s*(" + StringUtils.join(myMap.keySet(), "|") + ")"

    【讨论】:

    • Map实例调用keySet()的结果是Set,而Sets在Java中没有join方法。
    • @Pshemo:抱歉,我没有意识到这一点。我已经更新了使用 StringUtils 的解决方案。这行得通吗?
    【解决方案3】:

    你可以试试这个:

    String p = "\\d+ (?:";
    for (String key : yourMap.keySet())
       p += key + "|";
    p = p.substring(0, p.length() - 1) + ")";
    

    【讨论】:

      猜你喜欢
      • 2014-04-13
      • 2018-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-07
      • 1970-01-01
      • 2021-12-21
      相关资源
      最近更新 更多