【问题标题】:Regex: replacing a string with prefix capture except for a given prefix正则表达式:用前缀捕获替换字符串,除了给定的前缀
【发布时间】:2012-11-07 20:46:02
【问题描述】:

我想替换一个字符串,保留前缀,除非它包含特定前缀。

例如,任何像"(*)-bar" 这样的字符串都必须替换为"(*)-blah",除非"(*)" 匹配"baz"

foo-bar => should return foo-blah 
baz-bar => should remain baz-bar

到目前为止,我最好的方法是在替换时修剪前缀的最后一个字母:

echo "foo-bar" | sed s/"[^(baz)]-bar"/$1-blah/

【问题讨论】:

  • [^(baz)] 并不代表你认为的那样。 [^...] 匹配不是括号中的字符之一的单个字符。

标签: regex regex-negation


【解决方案1】:

使用消极的后视

s/(?<!baz)-bar/-blah/

大多数sed 实现没有这种高级正则表达式功能,但它应该可以在更现代的语言中使用,例如 perl。

【讨论】:

    【解决方案2】:

    使用 sed :

    $ echo "foo-bar" | sed '/^foo-baz/!s/^foo-.*$/foo-blah/'
    foo-blah
    $ echo "foo-baz" | sed '/^foo-baz/!s/^foo-.*$/foo-blah/'
    foo-baz
    

    如果我分解:

    echo "foo-baz" | sed '/^foo-baz/!s/^foo-.*$/foo-blah/'
                          |        |||                   |
                          +  regex +|+ substitution part +
                                    |
                                  negation of regex
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-18
      • 1970-01-01
      • 1970-01-01
      • 2015-03-21
      相关资源
      最近更新 更多