【问题标题】:Perl global substitution with look ahead and look behind?Perl 全局替换与前瞻后瞻?
【发布时间】:2013-11-09 20:27:59
【问题描述】:

我试图在 perl 中基于在某个匹配之前或之后不匹配的某个模式对字符串执行全局替换。基本上,我有一个 xml 标签,如果匹配出现在标签之前或之后的十个字符内,我想保留它,但如果没有,则删除 xml 标签。

所以,如果我有一个包含以下内容的字符串:

foo something<xml tag>bar<\xml tag> something

不会发生替换,但如果字符串是

something <xml tag>bar<\xml tag> something

它将被替换为:

something bar something

我尝试的是:

$string =~ s/(?<!foo.{0,10})<xml tag>(bar)<\/xml tag> |<xml tag>(bar)<\/xml tag>(?!.{0,10}foo)/$1/g;

但是我收到了这个错误:

Variable length lookbehind not implemented in regex

我不太确定该怎么做。帮忙?

【问题讨论】:

标签: regex perl substitution


【解决方案1】:

来自 perlretut

Lookahead "(?=regexp)" 可以匹配任意正则表达式,但lookbehind "(?

因此,如果单词在&lt;xml tag&gt;bar&lt;\xml tag&gt; 之前具有固定长度,则应使用它,否则您可能会使用多个正则表达式。

【讨论】:

    【解决方案2】:

    使用e 标志的一种方式:

    while (<DATA>) {
        s/((.{0,13})<xml\ tag>([^<]*)<\/xml\ tag>)(?!.{0,10}foo)/
        index($2,'foo') > -1 ? "$1" : "$2$3"/xe;
        print $_; 
    }
    
    __DATA__
    foo something<xml tag>bar</xml tag> something
    something <xml tag>bar</xml tag> something
    

    生产:

    foo something<xml tag>bar</xml tag> something
    something bar something
    

    【讨论】:

      猜你喜欢
      • 2012-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-27
      • 1970-01-01
      相关资源
      最近更新 更多