using negative conditions within regular expressions

删除回忆录丶 提交于 2019-12-04 12:18:32

问题


Is it possible to use negative matches within gsub expressions? I want to replace strings starting by hello except those starting by hello Peter

my-string.gsub(/^hello@/i, '')

What should I put instead of the @?


回答1:


Sounds like you want a negative lookahead:

>> "hello foo".gsub(/hello (?!peter)/, 'lala ') #=> "lala foo"
>> "hello peter".gsub(/hello (?!peter)/, 'lala ') #=> "hello peter"



回答2:


As Michael told you you need a negative lookahead.

For your example is something like:

my_string.gsub(/^hello(?! peter)( .*|$)/i, '')

This will replace in cases like:

"hello"
"hello Mom"
"hello "
"hello Mom and Dad"

And will ignore things like:

"hello Peter"
"hello peter"
"hellomom"
"hello peter and tom"


来源:https://stackoverflow.com/questions/6180556/using-negative-conditions-within-regular-expressions

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!