use v5.12;

# demo for:
# http://stackoverflow.com/questions/17039670/vertical-regex-matching-in-an-ascii-image


my $r = qr/
^
(?:
    (?:                   # match .+? characters
        .
        (?=               # counting the same number on the following two lines
            .*+\n
            ( \1?+ . )
            .*+\n
            ( \2?+ . )
        )
    )+?
    (?<= X )              # till the above consumes an X
    (?=                   # that matches the following conditions
        .*+\n
        \1?+
        (?<= X )
        .*+\n
        \2?+
        (?<= X )
    )
    (?=                   # count the number of matches
        .*+\n
        ( \3?+ . )        # the number of matches = length of $3
    )
)*                        # repeat as long as there are matches on this line
.*\n?                     # remove the rest of the line
/xm;


my @tests = split /(?:\r?\n){2,}/, <<TESTS;
X
X
X

..X....
..X....
..X....

..X.X..
..X.X..
....X..

..X....
..X....
...X...

..X....
...X...
..X....

....X..
.X..X..
.X.....

.X..X..
.X.X...
.X.X...

.X..X..
.X..X..
.X..X..

XXX
XXX
XXX

X.X.X
XXXXX
XXXXX
.X.X.


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
.

TESTS


for(my $i = 0; $i < @tests; ++$i){
    my $test = $tests[$i];
	say "Test #$i:";
	say "-" x 20;
	say "$test\n";
	
	$test =~ s/$r/$3/g;
	
	say "result: ", length($test), " ($test)";
	say "\n";
}
