PROGRAMMING

 
REMEMBERS




Last update:   29-10-2021

Else

This construct allows you to express an if/then/else within a regex. Matches an < IMG > html tag, either alone, or surrounded by < A > < /A>
 
$text = "<a href=''><img id=1></a> <img id=2>";

$text =~ s/
        (<a\s+[^>]+>\s*)?    #Match leading <A> tag, if there

        <img\s+[^>]+>        #Match <IMG> tag

        (?(1)\s*<\/a>)        #Match a closing <\/A>, if we'd matched an <a> before

        /IMG/gix;        #Replace all with IMG

print $text . "\n";        #Outputs: IMG IMG
    
... 1 lines
 
Without (?(1) ) it doesn't match second IMG
 
$text = "<a href=''><img id=1></a> <img id=2>";

$text =~ s/
    (<a\s+[^>]+> \s* )?    #Match leading <A> tag, if there

    <img\s+[^>]+>        #Match <IMG> tag

    (\s*<\/a>)        #Match a closing <\/A>, if we'd matched an <a> before

    /IMG/gix;        #Replace all with IMG

print $text . "\n";        #Outputs: IMG <img id=2>
    
... 1 lines
 
Participating In The Match    (2/2)

Participating in the match

The (1) in (?(1) ) tests whether the first set of capturing parentheses participated in the match. "Participating in the match" is very different from "actually matched some text". Consider these two approaches to matching a word optionally wrapped in "< >". (<)?\w+(?(1)>) works, but () does not.
 
$text = "<img> bold";

$text =~ s/(<)?\w+(?(1)>)/WORD/g;

print $text . "\n"; #Outputs: WORD WORD
    
In the second approach, (< ?) is not optional, so they "participate in the match". Matching words optionally wrapped in "< >"
 
$text = "<img> bold";

$text =~ s/(<?)\w+(?(1)>)/WORD/g;

print $text . "\n"; #Outputs: WORD bold
    

Questions    
Mechanics

        A B C D E F
🔔
1/1