Allen Liu
Allen Liu

Reputation: 4038

Alternatives in negative look-behind

I'm looking to match a string that is not preceded by a "]: " or a "(". First, I tried using the look-behind syntax for just one of the criteria at a time and it works:

/(?<!\]: )\b(.+)/i

/(?<!\()\b(.+)/i

Then when I try to combine both criteria using the or syntax in the look-behind, it breaks:

/(?<!(\]: |\())\b(.+)/i

I get an error saying:

RegexpError: invalid pattern in look-behind

Is there anything like Regexp.union that requires a string to match all the expressions? Any suggestions would be greatly appreciated.

Upvotes: 0

Views: 210

Answers (2)

Aran-Fey
Aran-Fey

Reputation: 43146

You can use two consecutive lookbehinds like this:

(?<!\()(?<!\]: )\b(.+)

Upvotes: 1

sawa
sawa

Reputation: 168091

From Oniguruma manual:

(?<=subexp)        look-behind
(?<!subexp)        negative look-behind

                     Subexp of look-behind must be fixed character length.
                     [D]ifferent character length is allowed in top level
                     alternatives only.
                     ex. (?<=a|bc) is OK. (?<=aaa(?:b|cd)) is not allowed.

                     In negative-look-behind, captured group isn't allowed, 
                     but shy group(?:) is allowed.

So just replace the captured group by a shy group:

/(?<!(?:\]: |\())\b(.+)/i

Upvotes: 0

Related Questions