Regular Expression For Duplicate Words

后端 未结 13 1982
终归单人心
终归单人心 2020-11-22 11:13

I\'m a regular expression newbie, and I can\'t quite figure out how to write a single regular expression that would "match" any duplicate consecutive words such as

13条回答
  •  温柔的废话
    2020-11-22 11:51

    Try this with below RE

    • \b start of word word boundary
    • \W+ any word character
    • \1 same word matched already
    • \b end of word
    • ()* Repeating again

      public static void main(String[] args) {
      
          String regex = "\\b(\\w+)(\\b\\W+\\b\\1\\b)*";//  "/* Write a RegEx matching repeated words here. */";
          Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE/* Insert the correct Pattern flag here.*/);
      
          Scanner in = new Scanner(System.in);
      
          int numSentences = Integer.parseInt(in.nextLine());
      
          while (numSentences-- > 0) {
              String input = in.nextLine();
      
              Matcher m = p.matcher(input);
      
              // Check for subsequences of input that match the compiled pattern
              while (m.find()) {
                  input = input.replaceAll(m.group(0),m.group(1));
              }
      
              // Prints the modified sentence.
              System.out.println(input);
          }
      
          in.close();
      }
      

提交回复
热议问题