使用现代正则表达式风格,如 PCRE/PHP、Perl、.NET 或类似的,可以确定如果 ASCII“图像”中存在由三个 X 组成的垂直线。
考虑以下正则表达式:
(?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
此表达式使用具有自引用捕获组的前瞻来计算X 之前每行的字符数。它尝试通过匹配前瞻中指定的条件来匹配垂直格式中的三个 X 字符。
在线演示: https://regex101 .com/r/Xb5FXl/2
虽然它不能在像 Perl 和 PCRE 这样的有限后向的正则表达式风格中直接解决,但可以通过操作匹配的字符串来间接确定计数。
以下解决方案通过匹配和计算匹配中出现三个 X 的部分中的字符数来修改 m.buettner 的“部分 PCRE 解决方案”。
^ (?: (?: # 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
此表达式与前一个表达式匹配相同的格式,但它添加了第三个捕获组并计算该组中匹配字符的长度。通过仅用第三个捕获组的内容替换匹配项,生成的字符串长度表示三 X 形式的数量。
Perl 中的示例用法:
$in =~ s/regex//gmx; $count = length $in;
在线演示: https://regex101.com/r/iqxY1a/1
测试用例:
Test #0: -------------------- X X X result: 1 (X) Test #1: -------------------- ..X.... ..X.... ..X.... result: 1 (.) Test #2: -------------------- ..X.X.. ..X.X.. ....X.. result: 1 (.) Test #3: -------------------- ..X.... ..X.... ...X... result: 0 () Test #4: -------------------- ..X.... ...X... ..X.... result: 0 () Test #5: -------------------- ....X.. .X..X.. .X..... result: 0 () Test #6: -------------------- .X..X.. .X.X... .X.X... result: 1 (.) Test #7: -------------------- .X..X.. .X..X.. .X..X.. result: 2 (.X) Test #8: -------------------- XXX XXX XXX result: 3 (XXX) Test #9: -------------------- X.X.X XXXXX XXXXX .X.X. result: 5 (XXXXX) Test #10: -------------------- 1....X....... 2..X..X...X.... 3X.X...X..X..... 4X....XXXXXX..... 5X..XXX........... 6.....X.......... 7.........X....X 8..X......X....X.... 9..X......X....X....X... A....X..... B.X..X.. C..... XXX XXX XXX . result: 8 (3458.XXX)
以上是正则表达式能否检测 ASCII 图像中垂直线结构中的三个 X?的详细内容。更多信息请关注PHP中文网其他相关文章!