MyNameWouldGoHere
MyNameWouldGoHere

Reputation: 165

Start at the penultimate character in capture group of regex php

I am trying to create a regex that only captures between the second to last and last occurrences of the surrounding characters (if you get what I mean).

My regex so far is this:

\[(.*?)]\{(.*?)\}/ig

This is my string:

[don't touch me] random text [touchme]{Secondcapturegroup}

As you can see by this screenshot, it's capturing everything from [don't all the way to [touchme]. I want it to effectively ignore [don't touch me] random text

don'ttouchme

I'm still learning regex, but I know there must be something :)

Upvotes: 0

Views: 255

Answers (1)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89629

You can use a character class that excludes the closing square bracket instead of using . (and in this way the non-greedy quantifier *? is no more needed)

\[([^]]*)]{([^}]*)}

In this way the attempt at the first opening square bracket will fail because the closing square bracket is not followed by an opening curly bracket.

With your pattern you obtain a wrong result because the regex engine parse your string from the left and try to succeed at each position (so the first position always win).

Note that the i modifier is useless.

Upvotes: 2

Related Questions