【问题标题】:How to make substitutions in string only after a certain anchor?如何仅在某个锚点之后在字符串中进行替换?
【发布时间】:2020-02-14 17:28:18
【问题描述】:

如何仅在某个锚点之后在字符串中进行替换?

我需要:

xtop.xnext.sig1 --> xtop.xnext-sig1
xtop.xnext.xlower.sig2 --> xtop.xnext-xlower-sig2

在 Perl 中使用优雅的 s///。有没有一种很酷的方法可以使用xtop.xnext 作为锚点(即所有'.' --> '-' 但仅在xtop.xnext 之后)而不是首先匹配然后使用多个命令拼接?

【问题讨论】:

    标签: regex perl substitution


    【解决方案1】:

    这是一种方法,首先使用匹配来设置起始位置,使用g 标志设置$strpos 属性,稍后可以与\G 断言一起使用以开始搜索给定位置:

    if ( $str =~ /xtop\.xnext/g ) {
        $str =~ s/\G[^.]*\K\./-/g;
    }
    

    更多信息请参见perldoc perlre

    【讨论】:

    • 这将要求. 立即跟随最后一场比赛。您想要在最后一场比赛之后的任何时候使用它,您可以插入 [^.]* 以允许在其间使用非点字符,然后使用 \K,这样这些字符就不会被替换。 s/\G[^.]*\K\./-/g
    • @Grinnz 感谢您的建议!我已经更新了问题
    【解决方案2】:

    这行得通:

    perl -p -e 's/(?:xtop\.xnext|\G)\K\.([^.]+)/-$1/g;'
    
    (?:  -- grouping only, don't create backref
    xtop.\xnext|\G   -- explicit text or position of last match
    \K     -- match from this position only
    \.     -- match the period
    ([^.]+)   -- capture for the purpose of the \G to be used later
    

    【讨论】:

      猜你喜欢
      • 2018-06-30
      • 1970-01-01
      • 1970-01-01
      • 2017-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-04
      • 1970-01-01
      相关资源
      最近更新 更多