'Conditional regular expression with Perl

Does Perl support conditional regular expression :

(?(condition)true-pattern|false-pattern)

i.e. if the condition is true then try to match the true pattern else try to match the false pattern

If Perl supported conditional regular expressions then why didn't this code print 1?

use strict;
use warnings;

$_ = 'AB';

if ( /(?(A)B|C)/ ) {
  print 1;
}


Solution 1:[1]

Perl supports conditional patterns.

Your regex doesn't just not match, it throws the following syntax error:

Unknown switch condition (?(A) in regex; marked by <-- HERE in m/(?( <-- HERE A)B|C)/

That's because A is not a valid condition.

Solution 2:[2]

I know I'm late this question but I'll try to explain my understanding of what the current regex is doing and how it can be adjusted.

Yes, Perl supports conditional expressions. However, the problem with this regular expression is that the condition has to either be a back reference or a zero-width assertion like a look-behind or look-ahead. In other words, the conditional can never consume any characters in the string.

So lets look at a couple ways that this can be rewritten.

One way would be to use a look-ahead and add the match to the then expression. So it could be rewritten to /(?(?=A)AB|C)/. This says if the string matches A then match and consume AB else match and consume C. This would then successfully match either AB or C.

Another way would be to use a capture group before the condition like so /(A)?(?(1)B|C)/. This says match and consume A zero or one time; if capture group 1 has a match then match and consume B else match and consume C. This would also successfully match either AB or C same as the previous example because the A is consumed and moves the match forward if it is present in the string.

The perldoc, as referenced in the other answer, explains other options you can use in the conditional but I feel the two examples above would be the most common to use.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ry-
Solution 2 Matthew Green