Home > OS >  Regex for ignoring matches
Regex for ignoring matches

Time:05-05

*test*
**test**
***test***

In the above case, I want to match only *test* ignoring all other cases in a multiline text. Can anyone give me guidance on how to do this using regular expression?

CodePudding user response:

This should work:

(?<!\*)\*test\*(?!\*)

It uses negative look around to check whether there is an * before of after the match.

You can check that it does what you want: https://regex101.com/r/G23yZL/1

(?!x) is a negative look ahead. It checks that what is after the match is not a x.

(?<!x) is a negative look behind. It checks that what is before the match is not x.

Note that there also exist positive look ahead (?=x) (resp. look behind (?<=x)). It will check if what is after (resp. behind) the match is a x.

  • Related