当前位置: 动力学知识库 > 问答 > 编程问答 >

perl - How to apply two conditions to a split?

问题描述:

I want to split on the letter "b" without removing it from the output. I only want to split on the "b" if it is not followed by a "c". How can I combine these two conditions? Here's what I've tried so far:

$val ="abbcdebffgbhiabbbcde";

@as = split(/(?<=b)/,"$val",) if !~/(bc)/g;

foreach (@as){

print "$_\n";

}

This is my expected output:

ab

bcdeb #here 'b' present but not split because succeeding 'c' is present.

ffgb

hiab

b

bcde #here 'b' present but not split because succeeding 'c' is present.

At the moment, my code splits on all the "b"s. How can I change it to combine the two conditions?

网友答案:

You want a negative lookahead assertion:

use strict;
use warnings;

my $val = "abbcdebffgbhiabbbcde";
my @as = split(/(?<=b)(?!c)/, $val);

print "$_\n" foreach @as;

This splits on any point preceded by the letter "b", as long as it is not followed by a "c". The (?!c) is a negative lookahead assertion, which means that any "b" followed by a "c" will not match.

Output:

ab
bcdeb
ffgb
hiab
b
bcde
网友答案:

Using a slight variation of my previous answer to your question:

$data = "abbcdebffgbhiabbbcde";

while ($data =~ /b[^c]/g) {
    print substr($data, 0, $+[0]-1, "") . "\n";
}
print $data,"\n";

Output:

ab
bcdeb
ffgb
hiab
b
bcde
分享给朋友:
您可能感兴趣的文章:
随机阅读: