The regex /abc$/
will match an abc
that does appear at the end of the line. How do I do the inverse?
I want to match abc
that isn't at the end of a line.
Furthermore, I'm going to be using the regex to replace strings, so I want to capture only abc
, not anything after the string, so /abc.+$/
doesn't work, because it would replace not only abc
but anything after abc
too.
What is the correct regex to use?
End of String or Line: $ The $ anchor specifies that the preceding pattern must occur at the end of the input string, or before \n at the end of the input string. If you use $ with the RegexOptions. Multiline option, the match can also occur at the end of a line.
Literal Characters and Sequences For instance, you might need to search for a dollar sign ("$") as part of a price list, or in a computer program as part of a variable name. Since the dollar sign is a metacharacter which means "end of line" in regex, you must escape it with a backslash to use it literally.
The meta character “^” matches the beginning of a particular string i.e. it matches the first character of the string. For example, The expression “^\d” matches the string/line starting with a digit. The expression “^[a-z]” matches the string/line starting with a lower case alphabet.
If you only want a match at the absolute very end of the string, use \z (lowercase z instead of uppercase Z).
/abc(?!$)/
(?!$)
is a negative lookahead. It will look for any match of abc that is not directly followed by a $
(end of line)
Tested against
applying it to your case:
ruby-1.9.2-p290 :007 > "aslkdjfabcalskdfjaabcaabc".gsub(/abc(?!$)/, 'xyz') => "aslkdjfxyzalskdfjaxyzaabc"
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