【问题标题】:Swap two specific words using regex使用正则表达式交换两个特定单词
【发布时间】:2022-01-23 13:17:18
【问题描述】:

我有这样的文字:

男孩女孩循环离开男孩女孩左右

我想用正则表达式交换boygirl。(注意:boy/girl出现无序。)所以我写了这个:

String str = "boy girl loop for get out boy girl left right";
String regex = "(\\bgirl\\b)|(\\bboy\\b)";
System.out.println(str.replaceAll(regex, "$2$1"));

但它不起作用。你能告诉我为什么并给出正确的解决方案吗?

【问题讨论】:

    标签: java regex regexp-replace


    【解决方案1】:

    你可以试试下面的代码。我只是在两者之间使用“临时”正则表达式来替换两个单词。

     String str = "boy girl loop for get out boy girl left right";
            String regexGirl = "(girl)";
            String regexBoy = "(boy)";
            System.out.println(str.replaceAll(regexGirl, "temp").replaceAll(regexBoy, "girl").replaceAll("temp", "boy"));
    

    【讨论】:

      【解决方案2】:

      您可以使用Matcher#replaceAll 在替换中使用“回调”:

      String str = "boy girl loop for get out boy girl left right";
      Matcher m = Pattern.compile("\\b(girl)\\b|\\b(boy)\\b").matcher(str);
      System.out.println( m.replaceAll(r -> r.group(2) != null ? "girl" : "boy") );
      // => girl boy loop for get out girl boy left right
      

      请参阅Java demo online

      这里,\b(girl)\b|\b(boy)\b 将整个单词 girl 匹配到第 1 组,将 boy 匹配到第 2 组。

      r -> r.group(2) != null ? "girl" : "boy" 替换检查组 2 是否匹配,如果不匹配,则替换为 girl,否则为 boy

      还有一种“用字典替换”的方法:

      String[] find = {"girl", "boy"};
      String[] replace = {"boy", "girl"};
               
      Map<String, String> dictionary = new HashMap<String, String>();
      for (int i = 0; i < find.length; i++) {
          dictionary.put(find[i], replace[i]);
      }
               
      String str = "boy girl loop for get out boy girl left right";
      Matcher m = Pattern.compile("\\b(?:" + String.join("|", find) + ")\\b").matcher(str);
      System.out.println( m.replaceAll(r -> dictionary.get(r.group())) );
      // => girl boy loop for get out girl boy left right 
      

      this Java demo

      【讨论】:

        猜你喜欢
        • 2021-08-05
        • 2019-10-24
        • 1970-01-01
        • 2018-08-30
        • 2021-04-20
        • 2021-04-20
        • 1970-01-01
        • 2022-08-18
        • 1970-01-01
        相关资源
        最近更新 更多