Home > Backend Development > PHP Tutorial > Can Regex Detect and Count Vertical 'X' Patterns in ASCII Art?

Can Regex Detect and Count Vertical 'X' Patterns in ASCII Art?

Mary-Kate Olsen
Release: 2024-11-16 12:15:03
Original
541 people have browsed it

Can Regex Detect and Count Vertical

Finding Vertical X Patterns in ASCII with Regex

Problem Statement

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.....
Copy after login

We aim to detect the following pattern:

X
X
X
Copy after login

where three Xs are aligned vertically.

Questions

  1. Is it possible to determine if such formations exist using regex?
  2. If so, is it possible to count the number of occurrences?

Answer to Question 1

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
Copy after login

Online Demo: https://regex101.com/r/YxPeXe/1

Answer to Question 2

Indirect Solution

To count the number of formations, we can perform the following substitution:

regex => 
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template