What is a regex to match a string NOT at the end of a line?

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

Leave a Comment