Regular expressions

Attempt to match a word if it is not contained in asterisks. Here is what I have:

(?<!\*)\b(word)\b(?!\*)

The problem is that it will not match *word or word* , since I want it to match every permutation, except for *word* .

+4
source share
3 answers

Try this solution, it should match any word, not just "word":

 (?<!\*)\b\w+\b|\b\w+\b(?!\*) 

The key point here is the search for two situations in which an asterisk may appear, that is, at the beginning of OR at the end of a word.

+3
source

Then you need alternation.

 (?<!\*)\bword\b|\bword\b(?!\*) 

See at Regexr .

Your problem is that the whole regex does not work as soon as one statement is true. My way to resolve * on the one hand, but it fails when * is on both sides.

+2
source

Some divertissement:
(?(?<=\*)word(?!\*)|word(?=\*))

Explanation:

 (? # if (?<=\*) # there is * before word(?!\*) # then match word not followed by * | # else word(?=\*) # match word followed by * ) # end if 

Demo version

+1
source

Source: https://habr.com/ru/post/1486773/


All Articles