Regular expression before or after

I would like to use regex to match string tofind

I have two options: 1st

before tofind

Te second -

tofind after 

How to combine the word tofind in two examples with one regular line?

I used

before (tofind) | (tofind) after 

He gave them in match 1 and in match 2

I would always get the result in match 1

I am using php:

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

Thank you

+4
source share
2 answers

You can use the reset branch :

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

now two capture groups have the same number.

Note: you can do the same with named capture (and you don't have to repeat the name of the capture group):

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

(?J), ( , , ):

(?J)(?:before (?<mycap>tofind)|(?<mycap>tofind) after)
+9

, , , (?|. lookbehind lookahead. 1, .

((?<=before )tofind|tofind(?= after))
+5

Source: https://habr.com/ru/post/1537145/


All Articles