fork download
  1. use v5.12;
  2.  
  3. # demo for:
  4. # http://stackoverflow.com/questions/17039670/vertical-regex-matching-in-an-ascii-image
  5.  
  6.  
  7. my $r = qr/
  8. ^
  9. (?:
  10. (?: # match .+? characters
  11. .
  12. (?= # counting the same number on the following two lines
  13. .*+\n
  14. ( \1?+ . )
  15. .*+\n
  16. ( \2?+ . )
  17. )
  18. )+?
  19. (?<= X ) # till the above consumes an X
  20. (?= # that matches the following conditions
  21. .*+\n
  22. \1?+
  23. (?<= X )
  24. .*+\n
  25. \2?+
  26. (?<= X )
  27. )
  28. (?= # count the number of matches
  29. .*+\n
  30. ( \3?+ . ) # the number of matches = length of $3
  31. )
  32. )* # repeat as long as there are matches on this line
  33. .*\n? # remove the rest of the line
  34. /xm;
  35.  
  36.  
  37. my @tests = split /(?:\r?\n){2,}/, <<TESTS;
  38. X
  39. X
  40. X
  41.  
  42. ..X....
  43. ..X....
  44. ..X....
  45.  
  46. ..X.X..
  47. ..X.X..
  48. ....X..
  49.  
  50. ..X....
  51. ..X....
  52. ...X...
  53.  
  54. ..X....
  55. ...X...
  56. ..X....
  57.  
  58. ....X..
  59. .X..X..
  60. .X.....
  61.  
  62. .X..X..
  63. .X.X...
  64. .X.X...
  65.  
  66. .X..X..
  67. .X..X..
  68. .X..X..
  69.  
  70. XXX
  71. XXX
  72. XXX
  73.  
  74. X.X.X
  75. XXXXX
  76. XXXXX
  77. .X.X.
  78.  
  79.  
  80. 1....X.......
  81. 2..X..X...X....
  82. 3X.X...X..X.....
  83. 4X....XXXXXX.....
  84. 5X..XXX...........
  85. 6.....X..........
  86. 7.........X....X
  87. 8..X......X....X....
  88. 9..X......X....X....X...
  89. A....X.....
  90. B.X..X..
  91. C.....
  92. XXX
  93. XXX
  94. XXX
  95. .
  96.  
  97. TESTS
  98.  
  99.  
  100. for(my $i = 0; $i < @tests; ++$i){
  101. my $test = $tests[$i];
  102. say "Test #$i:";
  103. say "-" x 20;
  104. say "$test\n";
  105.  
  106. $test =~ s/$r/$3/g;
  107.  
  108. say "result: ", length($test), " ($test)";
  109. say "\n";
  110. }
  111.  
Success #stdin #stdout 0s 3608KB
stdin
Standard input is empty
stdout
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)