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 ?
If you want to exclude a certain word/string in a search pattern, a good way to do this is regular expression assertion function. It is indispensable if you want to match something not followed by something else. ?= is positive lookahead and ?! is negative lookahead.
To replace or remove characters that don't match a regex, call the replace() method on the string passing it a regular expression that uses the caret ^ symbol, e.g. /[^a-z]+/ .
It's a negative lookahead, which means that for the expression to match, the part within (?!...) must not match. In this case the regex matches http:// only when it is not followed by the current host name (roughly, see Thilo's comment). Follow this answer to receive notifications.
The Match-zero-or-more Operator ( * ) This operator repeats the smallest possible preceding regular expression as many times as necessary (including zero) to match the pattern. `*' represents this operator. For example, `o*' matches any string made up of zero or more `o' s.
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.
/\b(?!boy)\S+/g
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With