使用 split() 拆分字符串并从该字符串创建一个数组,使单词和数字分开。
我知道前瞻和后视需要用于零宽度分割,所以我使用了它。
$string = 'A1BB22CCC333DDDD';
@string = split(/(?=\d+)|(?<=\d+)/,$string);
print "@string";
期望:
A 1 BB 22 CCC 333 DDDD
但是结果:
Variable length lookbehind not implemented in regex m/(?=\d+)|(?<=\d+)/ at jdoodle.pl line 2.
Command exited with non-zero status 255.
最佳答案
您可以使用类似 /(\d+)/
的模式来拆分字符串。
该模式包含一个捕获组;如 perldoc split 中所述:
If the PATTERN contains capturing groups, then for each separator, an additional field is produced for each substring captured by a group (in the order in which the groups are specified, as per backreferences);
考虑:
use strict;
use warnings;
my $string = "A1BB22CCC333DDDD";
my @result = split /(\d+)/, $string;
print "$_\n" for @result;
产量:
A
1
BB
22
CCC
333
DDDD
如果字符串以数字开头,上述解决方案将返回一个前导空元素。为避免这种情况,您可以按如下方式调整表达式:
my @result = grep length, split /(\d+)/, $string;
关于regex - 如何在 perl 中将字符串的字母和数字分开?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55432939/