Java recursive(?) repeated(?) deep(?) pattern matching

前端 未结 3 1786
旧巷少年郎
旧巷少年郎 2021-01-19 04:23

I\'m trying to get ALL the substrings in the input string that match the given pattern.

For example,

Given string: aaxxbbaxb
Pa

3条回答
  •  -上瘾入骨i
    2021-01-19 04:44

    (see: All overlapping substrings matching a java regex )

    Here is the full solution that I came up with. It can handle zero-width patterns, boundaries, etc. in the original regular expression. It looks through all substrings of the text string and checks whether the regular expression matches only at the specific position by padding the pattern with the appropriate number of wildcards at the beginning and end. It seems to work for the cases I tried -- although I haven't done extensive testing. It is most certainly less efficient than it could be.

      public static void allMatches(String text, String regex)
      {
        for (int i = 0; i < text.length(); ++i) {
          for (int j = i + 1; j <= text.length(); ++j) {
            String positionSpecificPattern = "((?<=^.{"+i+"})("+regex+")(?=.{"+(text.length() - j)+"}$))";
            Matcher m = Pattern.compile(positionSpecificPattern).matcher(text);
    
            if (m.find()) 
            {   
              System.out.println("Match found: \"" + (m.group()) + "\" at position [" + i + ", " + j + ")");
            }   
          }   
        }   
      }
    

提交回复
热议问题