1

Lets say I have this string:

key something.key() (.key)(key)

I would like regex to only match the word "keys" that are inside "[ ]"

[key] something.key() (.key)([key])

I have used this regex currently /(?!\.)key/g

But that only excludes dot and still selects word even if it startet with a dot.

Elias
  • 195
  • 2
  • 13

1 Answers1

2

Use negative character class to match not a dot:

[^\.]

Then add ^ to match not a dot or at the beginning of the string:

([^\.]|^)

Add ?: to the group to make it non-capturing.

(?:[^\.]|^)

Finally add a capturing group matching your word:

(?:[^\.]|^)(word)

You could achieve the same result using negative look-behind:

(?<!\.)word

Alas, JavaScript regex doesn’t implement it.

Pawel Decowski
  • 1,602
  • 2
  • 15
  • 23
  • This is a step forward but it also creates another problem I also encountered: The regex (?:[^\.]|^)(word) will select "(word" as a match, I would like it to only select "word". Or if a string contains "/word" then regex will select the whole "/word" and not just "word". – Elias Jul 06 '17 at 11:02
  • That’s why "word" is in a capturing group. Don’t use the whole match. Use the first capturing group — it won’t include the character before “word”. – Pawel Decowski Jul 06 '17 at 11:16
  • Here’s a demo: https://jsfiddle.net/ft2o3apL/6/ – Pawel Decowski Jul 06 '17 at 11:58