Jump to content

Example of pregex conditional subpatterns ?


androsleax

Recommended Posts

back reference condition

 

Pattern example:

 

(something )?((?(1)foo|fu)bar)

 

Pattern first looks for "something ". Then comes the back reference condition. If it exists, match for "foo". If it does not exist, match for "fu". Then match for "bar". Whole thing is wrapped in a group (2) to illustrate results easier.

 

Example 1: back reference #1 matched:

 

 

$string = "something foobar fubar";
preg_match("~(something )?((?(1)foo|fu)bar)~",$string,$match);
print_r($match);
Output:

Array
(
    [0] => something foobar
    [1] => something 
    [2] => foobar
)
Example 2: back reference #1 not matched:

 

 

$string = "foobar fubar";
preg_match("~(something )?((?(1)foo|fu)bar)~",$string,$match);
print_r($match);
Output:

Array
(
    [0] => fubar
    [1] => 
    [2] => fubar
)

lookahead condition

 

Pattern example: (?=12)[0-9]{3}

 

Goal is to match for a 3 digit number that starts with "12". The lookahead first checks to see if there's a "12". If there is, then proceed to match 3 digits.

 

Example 1: 3 digit number matched:

 

 

 

$string = "123";
preg_match("~(?=12)[0-9]{3}~",$string,$match);
print_r($match);
Output:

 

Array
(
    [0] => 123
)
Example 2: 3 digit number not matched:

 

 

 

$string = "193";
preg_match("~(?=12)[0-9]{3}~",$string,$match);
print_r($match);
Output:

 

Array
Array
(
)
The main thing to note about lookaheads and lookbehinds is that they do not actually consume anything. Normally each time something is matched in a string, that part of the string is consumed, meaning the regex engine's pointer moves on to the next character to try and match something. lookaheads/behinds do not make the pointer move. It peeks ahead (or behind) but stays in the same place.

 

 

lookbehind condition

 

Same thing as lookahead, except for looking back.

 

Pattern example: (?<=foo)bar

 

Match "bar" only if it was preceded by "foo".

 

Example 1: "bar" is preceded by "foo":

 

$string = "foobar";
preg_match("~(?<=foo)bar~",$string,$match);
print_r($match);
Output:

 

Array
(
    [0] => bar
)
Example 2: "bar} is not preceded by "foo":

 

 

 

$string = "fubar";
preg_match("~(?<=foo)bar~",$string,$match);
print_r($match);
Output:

 

Array
(
)

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.