In an ASCII image like the below:
....X....... ..X..X...X.... X.X...X..X..... X....XXXXXX..... X..XXX........... .....X.......... ..............X ..X...........X.... ..X...........X....X... ....X.....
We aim to detect the following pattern:
X X X
where three Xs are aligned vertically.
Yes, the following regex can identify the presence of vertical X formations:
(?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
Online Demo: https://regex101.com/r/YxPeXe/1
Indirect Solution
To count the number of formations, we can perform the following substitution:
regex =>
where regex is the above pattern. The resulting string length will equal the count of matches.
Online Demo: https://regex101.com/r/Tx6R63/1
The above is the detailed content of Can Regex Detect and Count Vertical 'X' Patterns in ASCII Art?. For more information, please follow other related articles on the PHP Chinese website!