Using the Perl Separation Function, but Saving Specific Separators

I have a string that I need to split into a specific character. However, I only need to split the string into one of these characters when it is surrounded by numbers. The same character exists elsewhere in the string, but will be surrounded by a letter - at least on one side. I tried using the split function as follows (using "x" as the character in question):

my @array = split /\dx\d/, $string; 

This function, however, removes the "x" and flanking digits. I would like to keep the numbers, if possible. Any ideas?

+4
source share
2 answers

Use zero-width statements:

 my @array = split /(?<=\d)x(?=\d)/, $string; 

This will correspond to the value of x , which is preceded by a digit, but does not consume the digits themselves.

+13
source

You can first replace the character that you want to split into something unique, and then split into this unique thing, something like this:

 $string =~ s/(\d)x(\d)/\1foobar\2/g; my @array = split /foobar/, $string; 
+1
source

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


All Articles