'Regex for ignoring matches

*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?



Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1