Is it possible to use negative matches within gsub expressions?
I want to replace strings starting by hello
except those starting by hello Peter
my-string.gsub(/^hello@/i, '')
What should I put instead of the @
?
Similarly, the negation variant of the character class is defined as "[^ ]" (with ^ within the square braces), it matches a single character which is not in the specified or set of possible characters. For example the regular expression [^abc] matches a single character except a or, b or, c.
Because the lookahead is negative, this means that the lookahead has successfully matched at the current position. At this point, the entire regex has matched, and q is returned as the match.
$ means "Match the end of the string" (the position after the last character in the string). Both are called anchors and ensure that the entire string is matched instead of just a substring.
Positive lookahead: (?= «pattern») matches if pattern matches what comes after the current location in the input string. Negative lookahead: (?! «pattern») matches if pattern does not match what comes after the current location in the input string.
Sounds like you want a negative lookahead:
>> "hello foo".gsub(/hello (?!peter)/, 'lala ') #=> "lala foo"
>> "hello peter".gsub(/hello (?!peter)/, 'lala ') #=> "hello peter"
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