Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using negative conditions within regular expressions

Tags:

regex

ruby

gsub

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 @?

like image 873
dgilperez Avatar asked May 30 '11 20:05

dgilperez


People also ask

How do you use negation in regex?

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.

What is negative look ahead in regex?

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.

What does '$' mean in regex?

$ 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.

What is positive and negative lookahead in regex?

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.


1 Answers

Sounds like you want a negative lookahead:

>> "hello foo".gsub(/hello (?!peter)/, 'lala ') #=> "lala foo"
>> "hello peter".gsub(/hello (?!peter)/, 'lala ') #=> "hello peter"
like image 51
Michael Kohl Avatar answered Sep 19 '22 11:09

Michael Kohl