Of course it is possible. In the end, we are talking about Perl regular expressions. But it will be pretty ugly:
say "55336"=~m{(\d)\1(\d)\2(\d)(?(?{$1+1==$3})|(*F))}?"match":"fail";
or pretty printed:
say "55336" =~ m{ (\d)\1 (\d)\2 (\d) (? (?{$1+1==$3}) # true-branch: nothing |(*FAIL) ) }x ? "match" : "fail";
What does it do? We collect numbers in conventional captures. At the end, we use the if-else pattern:
(? (CONDITION) TRUE | FALSE )
We can embed code in a regular expression with (?{ code }) . The return value of this code can be used as a condition. The verb (*FAIL) (short: (*F) ) causes the match to fail. Use (*PRUNE) if you need a branch, not an entire template.
Embedded code is also great for debugging. However, older pearls cannot use regular expressions inside this regular expression: - (
Thus, we can match many things and check them for validity inside the template itself. However, it would be better to do this outside of the template, for example:
"string" =~ /regex/ and (conditions)
Now to your main template N-3N-2N-1NNN+1N+2N+3 (I hope that he correctly disassembled it):
my $super_regex = qr{ # N -3 N-2 N-1 NN N+1 N+2 N+3 (\d)-3\1-2\1-1\1\1(\d)(\d)(\d) (?(?{$1==$2-1 and $1==$3-2 and $1==$4-3})|(*F)) }x; say "4-34-24-144567" =~ $super_regex ? "match" : "fail";
Or did you mean
my $super_regex = qr{ #N-3 N-2 N-1 NN N+1 N+2 N+3 (\d)(\d)(\d) (\d)\4 (\d)(\d)(\d) (? (?{$1==$4-3 and $2==$4-2 and $3==$4-1 and $5==$4+1 and $6==$4+2 and $7==$4+3})|(*F)) }x; say "123445678" =~ $super_regex ? "match" : "fail";
The scary thing is that they even work (with perl 5.12).
We could also generate parts of the template at a time with a construct (??{ code }) - the return value of this code is used as a template:
my $super_regex = qr{(\d)(??{$1+1})(??{$1+2})}x; say "234"=~$super_regex ? "match":"fail"
et cetera. However, I think that readability suffers more than that.
If you need more than nine captures, you can use named fragments with
(?<named>pattern) ... \k<named>
constructs. Content is also available in the %+ hash, see Perlvar for this.
To delve into the secrets of Perl regular expressions, I recommend reading perlre several times.