什么是匹配不在行尾的字符串的正则表达式? [英] What is a regex to match a string NOT at the end of a line?

查看:46
本文介绍了什么是匹配不在行尾的字符串的正则表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正则表达式 /abc$/ 将匹配出现在行尾的 abc.我如何做相反的事情?

The regex /abc$/ will match an abc that does appear at the end of the line. How do I do the inverse?

我想匹配不在行尾的 abc.

I want to match abc that isn't at the end of a line.

此外,我将使用正则表达式来替换字符串,所以我只想捕获abc,而不是字符串后面的任何内容,所以/abc.+$/ 不起作用,因为它不仅会替换 abc,还会替换 abc 之后的任何内容.

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)

经过测试

  • abcddee(匹配)
  • dddeeeabc(不匹配)
  • adfassdfabcs(匹配)
  • fabcddee(匹配)
  • abcddee (match)
  • dddeeeabc (no match)
  • adfassdfabcs (match)
  • fabcddee (match)

将其应用于您的案例:

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

这篇关于什么是匹配不在行尾的字符串的正则表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆