简体   繁体   中英

How can I split a string and use as prefix the split token on the splitted parts

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?
Eg 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?
Eg 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?

I am guessing you mean that you want to keep the split delimiter in the resulting strings, like so:

BlaBla
Topic Literature bla bla
Topic Math bla bla

In which case you can use a lookahead assertion:

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

Output:

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

Because the lookahead assertion is zero-length, it does not consume any part of the string when it matches.

Enclose the split in parentheses to capture it too:

#!/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;

Outputs:

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

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';

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 .....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM