I can't quite find what I am looking for on StackOverflow. I want to search for instances of a phrase that are not directly preceded by the phrase or directly followed by the phrase. For example, if the phrase is "foo"
and the word is "foo123foofoo123foo"
, the regex would replace the phrase (removing the word) to "123foofoo123"
.
How does one create a regular expression for this example?
I know to find everything but the phrase is ^(?!foo).*$
, but I want more like
not phrase + phrase + not phrase
as the phrase can occur elsewhere.
Sorry if this question is poorly worded or if I am misunderstanding. Thank you!
(?<=\bfoo).*?(?=foo\b)
with empty strings. Demo. Hover the cursor over each element of the regular expression at the link to obtain an explanation of its function.(?<=\bfoo)
is a positive lookbehind. It requires that the beginning of the match to be immediately preceded by"foo"
.(?<=foo\b)
is a positive lookahead. It requires that the beginning of the match to be immediately followed by"foo"
....\b
denotes a word boundary.\bfoo
restricts'foo'
from being preceded by a word character (a letter, digit or '_'). That prevents, for example,'goofoo'
from being matched.foo\b
prevents'foogoo'
from being matched. The question mark in.*?
means to match zero or more characters lazily. If the string were'foocatfoodogfoo'
,(?<=\bfoo).*?(?=foo\b)
would match'cat'
, whereas the greedy match(?<=\bfoo).*(?=foo\b)
(a greedy match) would match'catfoodog'
.