In an ASCII image like:
....X....... ..X..X...X.... X.X...X..X..... X....XXXXXX..... X..XXX........... .....X.......... ..............X ..X...........X.... ..X...........X....X... ....X.....
we'd like to find a simple vertical line formation of three Xs without using the best methods other than regex.
To determine if such a formation exists in PCRE/PHP, Perl, .NET or similar regexes, we can use the following expression:
(?xm) # ignore comments and whitespace, ^ matches beginning of line ^ # beginning of line (?: . # any character except \n (?= # lookahead .*+\n # go to next line ( ?+ . ) # add a character to the 1st capturing group .*+\n # next line ( ?+ . ) # add a character to the 2nd capturing group ) )*? # repeat as few times as needed X .*+\n # X on the first line and advance to next line ?+ # if 1st capturing group is defined, use it, consuming exactly the same number of characters as on the first line X .*+\n # X on the 2nd line and advance to next line ?+ # if 2st capturing group is defined, use it, consuming exactly the same number of characters as on the first line X # X on the 3rd line
Plain Matching
For direct matching and requiring the count as the number of matches, this question cannot be directly solved in PCRE or Perl due to limited lookbehind support.
Length/Indirect Solution
However, if the answer is accepted as the length of a match or substitution, then it can be answered with the following expression:
^ (?: (?: # match .+? characters . (?= # counting the same number on the following two lines .*+\n ( ?+ . ) .*+\n ( ?+ . ) ) )+? (?<= X ) # till the above consumes an X (?= # that matches the following conditions .*+\n ?+ (?<= X ) .*+\n ?+ (?<= X ) ) (?= # count the number of matches .*+\n ( ?+ . ) # the number of matches = length of ) )* # repeat as long as there are matches on this line .*\n? # remove the rest of the line
The above is the detailed content of Can You Find Vertical Lines of Three 'X's in an ASCII Image Using Regex?. For more information, please follow other related articles on the PHP Chinese website!