2016-08-01 30 views
-2

我寻求一个单一的UNIX /的Perl/PHP样式的正则表达式做文本字符串列表如下:正则表达式来重命名/修改重复的行

  • 搜索开头第一线'#'字符
  • 修改所有字符串的搜索字符串,但没有开头的'#',这样行也会以'#'开头。这些行可能有尾随文本(但不一定)。

这必须在一条路径上完成。

例如为:

some line 
# some string 
some line 
some line 
some line 
some string some other string 
some line 
some line 
some string 
some line 
some line 
some line 
some string some trailing text 
some line 

Regex101

所以我所寻求的是将匹配线# some string,然后在与some string启动其他线路的开头添加#正则表达式。这将匹配和修改都是线,

  • some string some other string - ># some string some other string
  • some string - ># some string
  • some string some trailing text - ># some string some trailing text

我想到做这样^(#?[^\r\n]+$)[\s\S]*(^\1[^\r\n]*$)+东西匹配所有这些事件,但我需要拆分这个来代替每个单独的事件...

谢谢。

+1

什么正则表达式你到目前为止已经试过? – AbhiNickz

+0

'^(#?[^ \ r \ n] + $)([\ s \ S] *)(^ \ 1 [^ \ r \ n] * $)+' – hoonose

回答

1

试图把它写成单个正则表达式听起来像是不可维护代码的秘诀。我会这样写:

my $prefix; 
while (<>) { 
    # If we find a line that starts with #, then set $prefix 
    if (/^# (.*)/) { 
    $prefix = $1; 
    } 

    # If $prefix is defined and we find a line that starts with $prefix, 
    # then prepend '#' 
    if (defined $prefix and /^$prefix/) { 
    $_ = "$prefix $_"; 
    } 

    print; 
} 
+0

谢谢。但是,这不是为了代码,而是作为文本编辑器宏的一个步骤,这就是为什么需要一次运行它。如果我可以使用一个循环,我会做到这一点。 – hoonose

+0

在提问时提及这样的限制可能是个好主意。 –

+0

戴夫,真的,谢谢,但我是要求一个正则表达式而不是代码。 – hoonose

0

可变的后面将是伟大的。
但大多数正则表达式引擎不支持。只有固定的背后。

但是,如果您可以反转该字符串列表。
然后你可能仍然可以在反转的文字上使用积极的向前看。更换后将文本反转。

一个非常简单的例子。

我们先从文字:

z 
# a 
a y 
a 
x 

现在我们扭转文本:

x 
a 
y a 
a # 
z 

现在我们全部更换(全球性的,多行)
(\w+$)(?=[\s\S]+\1 ?#)
通过\0 #

而我们得到:

x 
a # 
y a # 
a # 
z 

现在反向结果:

z 
# a 
# a y 
# a 
x