首页 > 后端开发 > php教程 > 您可以使用正则表达式在 ASCII 图像中找到由三个'X”组成的垂直线吗?

您可以使用正则表达式在 ASCII 图像中找到由三个'X”组成的垂直线吗?

Patricia Arquette
发布: 2024-11-08 12:42:02
原创
932 人浏览过

Can You Find Vertical Lines of Three 'X's in an ASCII Image Using Regex?

ASCII 图像中的垂直正则表达式匹配

问题

在 ASCII 图像中,例如:

....X.......
..X..X...X....
X.X...X..X.....
X....XXXXXX.....
X..XXX...........
.....X..........
..............X
..X...........X....
..X...........X....X...
....X.....
登录后复制

我们'我想找到一个由三个 X 组成的简单垂直线结构,而不使用除正则表达式之外的最佳方法。

问题 1:这种结构是否存在

确定 PCRE/ 中是否存在这样的结构PHP、Perl、.NET 或类似的正则表达式,我们可以使用以下表达式:

(?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
登录后复制

问题 2:计算此类形式

简单匹配
For直接匹配并要求计数为匹配数,由于lookbehind支持有限,这个问题无法在PCRE或Perl中直接解决。

长度/间接解决方案
但是,如果答案被接受为匹配或替换的长度,然后可以用以下表达式回答:

^
(?:
    (?:                   # 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
登录后复制

以上是您可以使用正则表达式在 ASCII 图像中找到由三个'X”组成的垂直线吗?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板