Ruby gsub/regex to find all chars but not specific words

229 Views Asked by At

My Objective:
I have a string like so:

"O_1324||T_6789||EC_67889&&(IC_12345||chicken)||true&&false"

My dream is to use a gsub regex to identify [a-zA-z0-9_] and replace them with something ("false" if you must know). However I don't want to replace the words "true" or "false".

What have I tried
I have been using the super friendly Rubular with little success.

I can get all the "words" (non operators) like so: (\w+)

I tried matching all the "words" except "true" like so: (?!true)(\w+)

This did not work. It unmatches only the "t" in true.

1

There are 1 best solutions below

0
On BEST ANSWER

You can use following regex :

\b(?:(?!true|false)\b)\w+\b

see demo https://regex101.com/r/eX6rE6/1

Note that you need to use word boundary for matching words. and put the negative look-ahead before \w+ not after!