【问题标题】:Multiple replace option for a string in java regexjava正则表达式中字符串的多个替换选项
【发布时间】:2015-04-21 18:32:46
【问题描述】:

如何用不同的替换正则表达式替换不同的匹配 如果我有两个由 | 分隔的匹配选项,对于每个匹配项,我想引用匹配的字符串或子字符串。 如果我有

Pattern p = Pattern.compile("man|woman|girls");
Matcher m = p.matcher("some string");

如果匹配是“男人”,我想使用与匹配“女人”或“女孩”不同的替换。

我查看了Most efficient way to use replace multiple words in a string,但不明白如何引用匹配本身。

【问题讨论】:

    标签: java android


    【解决方案1】:

    考虑稍微改进您的模式以添加单词边界,以防止它仅修补部分单词,例如 man 可以匹配 mandatory

    (顺便说一句:如果您想替换具有相同开头的单词,例如manmanual,您应该在正则表达式中将manual 放在man 之前,否则man 将消耗<man>ual 部分这将阻止ual 匹配。所以正确的顺序是manual|man)

    所以你的正则表达式看起来更像

    Pattern p = Pattern.compile("\\b(man|woman|girls)\\b");
    Matcher m = p.matcher("some text about woman and few girls");
    

    接下来您可以做的就是简单地将配对 originalValue -> replacement 存储在某个集合中,这样您就可以轻松获得价值替换。最简单的方法是使用地图

    Map<String, String> replacementMap = new HashMap<>();
    replacementMap.put("man", "foo");
    replacementMap.put("woman", "bar");
    replacementMap.put("girls", "baz");
    

    现在您的代码可能如下所示:

    StringBuffer sb = new StringBuffer();
    while(m.find()){
        String wordToReplace = m.group();
        //replace found word with with its replacement in map
        m.appendReplacement(sb, replacementMap.get(wordToReplace));
    }
    m.appendTail(sb);
    
    String replaced = sb.toString();
    

    【讨论】:

      【解决方案2】:

      你可以的

      str = 
         str.replace("woman", "REPLACEMENT1")
         .replace("man", "REPLACEMENT2")
         .replace("girls", "REPLACEMENT3");
      

      【讨论】:

      • 好的,谢谢,但希望使用这种性质的东西 while (m.find()) { m.appendReplacement(); }。发现它并没有使用太多的 cpu 资源
      猜你喜欢
      • 2014-08-25
      • 1970-01-01
      • 2010-10-04
      • 2017-07-12
      • 1970-01-01
      • 2018-07-13
      • 1970-01-01
      • 1970-01-01
      • 2017-02-04
      相关资源
      最近更新 更多