Home > Mobile >  Regex to match string except when it is placed between two characters
Regex to match string except when it is placed between two characters

Time:03-25

Given, input that will look like

match-me~match-me~ match-me ~match-me~
  • where, match-me is dynamic, it can be a word or a special character, basically anything (for example & or “)

I need to find all match-me instances, whereas ignoring matches that are in between tilde symbols ~match-me~.

Please do not refer me to similar questions, as I googled a lot of them, but none of them really helped. I am not a regex expert but would appreciate if answer worked the with JavaScript.

CodePudding user response:

^match-me|[^~]match-me[^~]

This matches any string beginning with match-me or any string matching match-me that is not preceded by and succeeded by a tilde.

[^~] matches any character that is not a tilde.

https://regexone.com/lesson/excluding_characters

CodePudding user response:

Try this:

let word = "match-me";
let pattern = new RegExp("(?<!~)" word "(?!~)", "gm");
var match = pattern.exec("match-me~match-me~ match-me ~match-me~");
if (match) {
    console.log("Match found at location:"   match.index);
}

What you need is look arounds.

Here you can dynamically change your "match-me" word, and still find the correct match.

RegExp("(?<!~)" word "(?!~)", "gm")

(?<!~) negative lookbehind, checks if a ~ is not preceding the current position of the string.
word   adds word to the regex pattern
(?!~)  negative lookahead, checks if a ~ is not following the current position
gm     global and multiline flags

Test regex here: https://regex101.com/r/szkbLa/1

  • Related