How to capture regular expression rotation match groups with split?

I have a line

my $foo = 'one#two#three!four#five#six'; 

from which I want to extract parts that are separated by either # or ! . This is easy enough with split :

 my @parts = split /#|!/, $foo; 

An additional requirement is that I also need to fix the exclamation points. So I tried

 my @parts = split /#|(!)/, $foo; 

This, however, returns either an undef value or an exclamation point (which is also clearly indicated in the split specification).

So, I eliminated unnecessary undef values โ€‹โ€‹with grep :

 my @parts = grep { defined } split /#|(!)/, $foo; 

It does what I want.

But I was wondering if I can change the regex so that I don't have to call grep as well.

+5
source share
2 answers

When you use split , you can skip empty captures after a match is found (since there are always as many frames in a match as defined in the regular expression). Here you can use the matching approach:

 my @parts = $foo =~ /[^!#]+|!/g; 

Thus, you will match 1 or more characters other than ! and # (with [^!#]+ alternative), or an exclamation mark, several times ( /g ).

+5
source

Use "an empty line followed by an exclamation mark or an empty line followed by an exclamation mark" instead of your second alternative:

 my @parts = split /#|(?=!)|(?<=!)/, $foo; 

Demo: https://ideone.com/6pA1wx

+2
source

Source: https://habr.com/ru/post/1265947/


All Articles