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 question):
我有一个字符串,我需要拆分某个字符。但是,当它的两侧是数字时,我只需要在其中一个字符上拆分字符串。字符串中的其他位置存在相同的字符,但两侧会有一个字母 - 至少在一侧。我试图使用split函数如下(使用“x”作为问题):
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?
但是,此功能会删除“x”和侧翼数字。如果可能,我想保留数字。有任何想法吗?
2 个解决方案
#1
13
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.
这将匹配数字之前和之后的x,但不会消耗数字本身。
#2
1
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;
#1
13
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.
这将匹配数字之前和之后的x,但不会消耗数字本身。
#2
1
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;