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

前端 未结 3 1784
旧巷少年郎
旧巷少年郎 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: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.

提交回复
热议问题