Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex before or after

Tags:

regex

php

I would to use regex to match the string tofind

I have two possibilities the 1st

before tofind

Te second is

tofind after 

How to match the word tofind in the two examples with one regex line?

I used

before (tofind) | (tofind) after 

It gave them on the match 1 and the match 2

I would have the result always in array match 1

I'm using php :

if (preg_match("/before (tofind) | (tofind) after/", $content, $result))
        return trim($result[1]);

thank you

like image 649
amorino Avatar asked Dec 09 '22 08:12

amorino


1 Answers

You can use the branch reset feature:

(?|before (tofind)|(tofind) after)

now the two capture groups have the same number.

Note: you can do the same with a named capture (and no need to repeat the name of the capture group):

(?|before (?<mycap>tofind)|(tofind) after)

or using the (?J) modifier that allows duplicate names (must be placed at the begining before the named groups, it is not available as a global modifier you can put after the end delimiter):

(?J)(?:before (?<mycap>tofind)|(?<mycap>tofind) after)
like image 200
Casimir et Hippolyte Avatar answered Dec 12 '22 22:12

Casimir et Hippolyte