0

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!

3
  • Assuming your regex engine supports lookbehinds (in which case it will alway support lookaheads), you can substitute matches of (?<=\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".... Commented Feb 7, 2022 at 0:59
  • ...\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'. Commented Feb 7, 2022 at 1:10
  • Did you find your solution? If not tell us what programming language you are working in.
    – user18098820
    Commented Mar 7, 2022 at 7:03

2 Answers 2

0

In many languages we can refer the the groups in brackets and use them in the replace. In this example the first and third groups are what we don't want and the second is what we want to keep.

import re

word = "foo123foofoo123foo"
print(re.sub(r'(foo)(.*)(foo)',r'\2',word))

# output = 123foofoo123
0

In a programming language that supports the PCRE flavor you can use this pattern.

\b(?=\w+(?<p>foo))(?!\g<p>|\w+\g<p>\b)\w+\b

The first lookahead (?=\w+(?<p>foo)) checks if there's a foo. The second lookahead (?!\g<p>|\w+\g<p>\b) checks if it doesn't start with the phrase, nor end with it.

In a regex flavor that doesn't support named groups it would be a pattern like this :

\b(?=\w+foo)(?!foo|\w+foo\b)\w+\b

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.