Php regex: problem with lookbehind and lookahead and greed

It should be simple, but I’m noob, and I can’t let life understand me. I am trying to use a regular expression to match text inside special open / close tags: [p2] [/ p2]

So in this text:

apple [p2]banana[/p2] grape [p2]lemon[/p2]

it should match the banana and lemon. The regular expression that I have developed so far:

(?<=\[p2\]).+(?=\[\/p2\])

But it is too greedy. It matches the “b” in the banana and ends with the “n” in the lemon, matching the banana [/ p2] grapes [p2] lemon . How to choose the right banana and lemon?

+5
source share
2 answers

This should do it:

(?<=\[p2\]).+?(?=\[\/p2\])

, .

+5

regex perl ? + *, , . , .

0

All Articles