开发者

Using the Perl split function, but keeping certain delimiters

I have a string that I need to split on a certain character. However, I only need to split the string on one of those characters when it is flanked by digits. That same character exists in other places in the string, but would be flanked by a letter -- at least on one side. I have tried to use the split function as follows (using "x" as the character in quest开发者_StackOverflow社区ion):

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

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


Use zero-width assertions:

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

This will match an x that is preceded and followed by a digit, but doesn't consume the digits themselves.


You could first replace the character you want to split on with something unique, and then split on that unique thing, something like this:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜