正则表达式-匹配下一个匹配项

问题描述

| 我想遍历文本的匹配项,要匹配的块以数字开头,然后是制表符。 我的开始比赛是
^\\d+\\t
,但是有没有办法表明我希望包括这场比赛在内的所有文字一直到下一场比赛? 输入数据:
1       111.111.111.111
111.111.111.111
                    Host IP     111.111.111.111
111.111.111.111
111.111.111.111         Host IP     TCP             app     11111,11111,11111      Allow
2       111.111.111.111
111.111.111.111
111.111.111.111         Host IP     111.111.111.111
111.111.111.111         Host IP     TCP             app     11111,11111      Allow
3       111.111.111.111
111.111.111.111         Host IP     111.111.111.111
111.111.111.111
111.111.111.111
111.111.111.111         Host IP     TCP             app     11111,11111      Allow
4       111.111.111.111
111.111.111.111
111.111.111.111
111.111.111.111         Host IP     111.111.111.111
111.111.111.111         Host IP     TCP             app     11111,11111      Allow
我正在使用Perl。     

解决方法

以下正则表达式应做您想做的:
^\\d+\\t(?:[^\\d]+|[\\d]+(?!\\t))*
这将匹配一些数字,后跟一个制表符,然后匹配任意数目的非数字或没有后跟制表符的数字。
my @matches = $data =~ /^\\d+\\t(?:[^\\d]+|[\\d]+(?!\\t))*/mg;
编辑:好的,这应该工作!     ,可能是这个吗?
/^\\d+\\t.*?(?:\\z|^\\d+\\t)/ms
    ,
while (/
    \\G
    ( \\d+\\t )
    ( (?: (?! \\d+\\t ) . )* )
/xg) {
    print(\"match:  $1\\n\");
    print(\"buffer: $2\\n\");
}
    ,样本输入和预期结果会有所帮助,因为我不确定我知道您在寻找什么。 如果您只匹配一种模式,则可以拆分字符串:
my $string = \"text\\n1\\ttest\\n2\\tend\\n\";
my @matches = split /^(\\d+)\\t/m,$string;
shift @matches; # remove the text before the first number
print \"[$_]\\n\" for @matches;

__END__
Output:
[1]
[test
]
[2]
[end
]
如果您匹配的多个模式Perl具有特殊的变量,则可以让您找到匹配的开始和结束位置。可以用来提取两次匹配之间的结果。
use English qw(-no_match_vars);

my $string = \"1\\ttestEND\\n2\\ttextEND\\n\";
if ($string =~ /^\\d+\\t/) {
    my $last_match_end = $LAST_MATCH_END[0];

    if ($string =~ /END/cg) {
        my $last_match_start = $LAST_MATCH_START[0];
        my $len = $last_match_start - $last_match_end;
        print substr($string,$last_match_end,$len) . \"\\n\"
    }
}
__END__
Output:
test