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

前端 未结 3 1785
旧巷少年郎
旧巷少年郎 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条回答
  • 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 + ")");
            }   
          }   
        }   
      }
    
    0 讨论(0)
  • 2021-01-19 04:53

    One thing you could do is:

    • Create all possible Substrings that are 4 characters or longer (good luck with that if your String is large)
    • Create a new Matcher for each of these substrings
    • do a match() instead of a find()
    • calculate the absolute offset from the substring's relative offset and the matcher info
    0 讨论(0)
  • 2021-01-19 04:56

    you are in effect searching for the strings ab, a_b, and a__b in an input string, where _ denotes a non-whitespace character whose value you do not care about.

    That's three search targets. The most efficient way I can think of to do this would be to use a search algorithm like the Knuth-Morris-Pratt algorithm, with a few modifications. In effect your pseudocode would be something like:

    for i in 0 to sourcestring.length
        check sourcestring[i] - is it a? if so, check sourcestring[i+x] 
           // where x is the index of the search string - 1
        if matches then save i to output list
        else i = i + searchstring.length
    

    obviously if you have a position match you must then check the inner characters of the substring to make sure they are alphabetical.

    run the algorithm 3 times, one for each search term. It will doubtless be much faster than trying to do the search using pattern matching.

    edit - sorry, didn't read the question properly. If you have to use regex then the above will not work for you.

    0 讨论(0)
提交回复
热议问题