Search code examples
phpregexpreg-matchpreg-match-all

regex to only match a full set of two-part pattern (kinda non-greedy)


I use preg_match_all to get all matches of a two-part pattern as:

/<(.*?)>[:|\s]+{(.*?)}/

In a string like:

<First>: something <second>: {Second} something <Third>: {Third}

I want to match:

<second>: {Second}

instead of:

<First>: something <second>: {Second}

Working Example

Where did I do wrong?


Solution

  • Use limited repeated set instead of lazy repetition inside the brackets:

    <([^>]*)>[:\s]+{(.*?)}
    

    The change is to replace <(.*?)> with <([^>]*)>. The initial version matches the first < then takes lazily any character until it finds :{Second}. If you restrict repetition, regex engine will try to start with <First>, but when it doesn't find :{...} after that, it'll try with the next <

    Demo