Home > Software design >  lookbehind combined with negative lookbehind
lookbehind combined with negative lookbehind

Time:04-06

I to match in javascript any string after nomatch if any for example "test 1 test2" in these 2 cases :

nomatch test1 test2

and

test1 test2

I tried https://regex101.com/r/qS4L1l/1

((?<=nomatch )\s*)(. )|(?<!nomatch )(. )

but it will include nomatch whereas I don't want to.

CodePudding user response:

If you target ECMAScript 2018 compatible JavaScript environments, you can use

(?<=nomatch\s |^(?!.*nomatch\s)). 

See the regex demo. Here, any one or more chars other than line break chars as many as possible are matched only if they are immediately preceded with nomatch and then one more whitespaces, or, if the current position is the start of string and after that there is no nomatch substring with a whitespace after after any zero or more chars other than line break chars.

Since you need to replace the parts matched with . , you can also consider using

text.replace(/^(.*?nomatch\s )?\S.*/, '$1<NEW TEXT>')

See this regex demo. Details:

  • ^ - start of string
  • (.*?nomatch\s )? - Group 1: an optional sequence of any zero or more chars other than line break chars as few as possible, then nomatch and one or more whitespaces
  • \S - a non-whitespace
  • .* - the rest of the line.

The $1 in the replacement string stands for the Group 1 value.

const texts = ['This is a nomatch test1 test2','nomatch test1 test2','test1 test2'];
const re = /^(.*?nomatch\s )?\S.*/;
for (const text of texts) {
  console.log(text.replace(re, '$1<NEW TEXT>'));
}

  • Related