Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
381 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
/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" 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...