alias51
alias51

Reputation: 8648

How to exclude a variable pattern from a selection

I have the following string:

Lorem ipsum {{ var1 }} dolar epsum <a href="{{ var2 }}">solar</a> hello goodbye. {{var3}} var {{ var4 }}

How do I capture all occurances of {{ var }} but not those between double quotes "{{ var2 }}"?

I have tried (?!")({{.*?}}) but it still captures all instances of {{ var }}.

Example here: https://regex101.com/r/zfjSI7/1

Upvotes: 2

Views: 246

Answers (1)

bobble bubble
bobble bubble

Reputation: 18555

As mentioned you need to use a lookbehind, not a lookahead. Further if there are no { } inside, use of a negated class will be more efficient than a lazy dot and stay inside: (?<!"){{[^}{]+}}


If you're on PHP/PCRE/Python with PyPI regex you can skip stuff by using verbs (*SKIP)(*F).

Skip quoted parts:
"[^"]*"(*SKIP)(*F)|{{[^}{]+}}
Or skip anchors:
<a\b[^><]*>(*SKIP)(*F)|{{[^}{]+}}


Another idea is to check for being outside angle brackets by use of a lookahead.
{{[^}{]+}}(?![^><]*>)

Upvotes: 3

Related Questions