How to split data with a separation value?

How to split data using a specific letter, but the split data is present in the previous dividing line.

My perl code

$data ="abccddaabcdebb";
@split = split('b',"$data");
foreach (@split){
    print "$_\n";
}  

This code presents the outputs, but the expected outputs:

ab
ccddaab
cdeb
b

How can i do this

+4
source share
3 answers

You can use lookbehind to save b:

$data ="abccddaabcdebb";
@split = split(/(?<=b)/, $data);    
foreach (@split){
    print "$_\n";
}  

will print

ab
ccddaab
cdeb
b
+3
source

You will need a positive appearance if you want to include the letter b, since the exclusion is excluded from the resulting list.

my $data ="abccddaabcdebb";
my @split = split(/(?<=b)/, $data);
foreach (@split) {
    print "$_\n";
}  

From perldoc -f split

Everything in EXPR that matches PATTERN is interpreted as a delimiter that separates EXPR from substrings (called "fields") that do not include a delimiter.

+2

The first parameter splitdetermines what separates the elements you want to extract. bDon't share your elements that you want, as this is actually part of what you want.

You can specify the separation after busing

my @parts = split /(?<=b)/, $s;

You can also use

my @parts = $s =~ /[^b]*b/g;

Side note:

split /(?<=b)/

splits

a b c b b

at three points

a b|c b|b| 

therefore, the result is four lines

  • ab
  • cb
  • b
  • Empty line

Fortunately, it splitremoves trailing empty lines from its default result, so three needed lines are called instead.

  • ab
  • cb
  • b
+1
source

All Articles