简体   繁体   中英

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

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?

/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

  • ddee (match) ddee(匹配)
  • dddeee (no match) (不匹配)
  • adfassdf s (match) s(匹配)
  • f ddee (match) ddee(匹配)

applying it to your case:

ruby-1.9.2-p290 :007 > "aslkdjfabcalskdfjaabcaabc".gsub(/abc(?!$)/, 'xyz')
  => "aslkdjfxyzalskdfjaxyzaabc" 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM