59

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?

stema
  • 90,351
  • 20
  • 107
  • 135
Tim
  • 6,079
  • 8
  • 35
  • 41
  • For a slightly different problem, matching unless a particular character (or set of characters) is at the end of the line (say, underscore (`_`)): `[^_]$` – Peter Mortensen Dec 02 '21 at 22:22

1 Answers1

90
/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

  • abcddee (match)
  • dddeeeabc (no match)
  • adfassdfabcs (match)
  • fabcddee (match)

applying it to your case:

ruby-1.9.2-p290 :007 > "aslkdjfabcalskdfjaabcaabc".gsub(/abc(?!$)/, 'xyz')
  => "aslkdjfxyzalskdfjaxyzaabc" 
Ben
  • 13,297
  • 4
  • 47
  • 68
  • 4
    For anyone else looking for it, in Vim the negative lookahead is [`\@!`](https://stackoverflow.com/a/21148678/1717828). – user1717828 Feb 15 '20 at 01:36
  • I needed to replace spaces in the middle and this pattern didn't cut it, but switching the 2 parts did it: `(?!$)\s` – juliangonzalez May 14 '20 at 17:33