0

If I want to split a string by a regex, how can I get the splitter string and as a prefix the part that we split on?
E.g. if I have: "BlaBla Topic Literature bla bla Topic Math bla bla"
And I want to split on Topic and get as the splitter string the Topic as well how do I do that?
E.g. split ('Topic[^:]', $string)
Will return: Literature bla bla but I want to return whatever matched in the split and the splitter string. How do I do that?

4

4 回答 4

3

我猜你的意思是你想在结果字符串中保留分割分隔符,如下所示:

BlaBla
Topic Literature bla bla
Topic Math bla bla

在这种情况下,您可以使用前瞻断言:

use Data::Dumper;
my $str = "BlaBla Topic Literature bla bla Topic Math bla bla";
my @result = split /(?<=Topic[^:])/, $str;
print Dumper \@result;

输出:

$VAR1 = [
          'BlaBla ',
          'Topic Literature bla bla ',
          'Topic Math bla bla'
        ];

因为前瞻断言的长度为零,所以它在匹配时不会消耗字符串的任何部分。

于 2013-10-03T13:21:01.917 回答
0

Use positive look-ahead assertion:

split("(?=Topic[^:])",$input)

use Data::Dumper;
$x="BlaBla Topic Literature bla bla Topic Math bla bla";
@y=split("(?=Topic[^:])",$x);
print Dumper(@y);'

$VAR1 = 'BlaBla ';
$VAR2 = 'Topic Literature bla bla ';
$VAR3 = 'Topic Math bla bla';
于 2013-10-03T13:19:22.740 回答
0

Use a non capturing look ahead:

perl -le "$s='BlaBla Topic Literature bla bla Topic Math bla bla';print $_ for split '(?=Topic[^:])', $s"

.....

Topic Literature .....

Topic Math .....

于 2013-10-03T13:19:48.160 回答
0

将拆分括在括号中以捕获它:

#!/usr/bin/perl
use strict;
use Data::Dumper;

my $file = "BlaBla Topic Literature bla bla Topic Math bla bla";

my (@new) = split('(Topic[^:])', $file);


print Dumper \@new;

输出:

$VAR1 = [
          'BlaBla ',
          'Topic ',
          'Literature bla bla ',
          'Topic ',
          'Math bla bla'
        ];
于 2013-10-03T13:13:47.227 回答