Matzy schneider
Matzy schneider

Reputation: 118

Regex exclude doesn't exclude string only first character

Firstly we have the following string:

aaa{ignoreme}asdebla bla f{}asdfdsaignoreme}asd

We want our regex to find the whitespaces and any special charsacters like {}, but if after { comes exactly ignoreme} then exclude it

This is where we are right now:

(?!{ignoreme})[\s\[\]{}()<>\\'"|^`]

The problem is that our regex finds the } after ignoreme

Here is the link https://regex101.com/r/bU1oG0/2

Any help is appreciated, Thanks

Upvotes: 3

Views: 268

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626861

The point is that the } is matched since your (?!{ignoreme}) lookahead only skips a { followed with ignoreme} and matches a } since it is not starting a {ignoreme} char sequence. Also, in JS, you cannot use a lookbehind, like (?<!{ignoreme)}.

This is a kind of issue that can be handled with a regex that matches what you do not need, and matches and captures what you need:

/{ignoreme}|([\s[\]{}()<>\\'"|^`])/g

See the regex demo

Now, {ignoreme} is matched (and you do not have to use this value) and ([\s[]{}()<>\\'"|^`]) is captured into Group 1 the value of which you need to use.

Upvotes: 5

Related Questions