Say I have a sentence:
I am a good buy and bad boy too
How to select every word except boy in this sentence using regular expression ?
Say I have a sentence:
I am a good buy and bad boy too
How to select every word except boy in this sentence using regular expression ?
You can use negative look behind:
\w+\b(?<!\bboy)
Or negative look ahead since not all support negative look behind
(?!boy\b)\b\w+
You can read about negative look ahead here
Try:
\b(?!boy\b).*?\b
which means:
\b
)Note: the word break matches the start of the string, the end of the string and any transition from word (number, letter or underscore) to non-word character or vice versa.
If you use "boy" as splitter, you would get remaining parts. You could use those as selection keys.
>>> re.split("boy","I am a good buy and bad boy too")
['I am a good buy and bad ', ' too']
As alternative, if possessive quantifiers are available, you can use;
\w+(?<!boy)
It takes generally fewer steps than using world boundaries.
I tested the following with http://regex101.com:
\b(?!boy)\S+|\w*\b$
This provides the list of all words delimited by spaces, but excludes only the word "boy" as asked.
Which language? Why do you want to use a regex?
answer = yourString.Replace( "boy", "" );