using negative conditions within regular expressions

前端 未结 2 1208
悲哀的现实
悲哀的现实 2021-02-09 14:02

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

2条回答
  •  悲&欢浪女
    2021-02-09 14:30

    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"
    

提交回复
热议问题