regex - 如何在 perl 中将字符串的字母和数字分开?

标签 regex string perl split substitution

使用 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/

相关文章:

c# - 将正则表达式的匹配结果转换为字符串列表

java - 正则表达式匹配硬模式

javascript - 当使用可选参数调用某个函数时,如何在某些文件中搜索案例?

c - 如何用一个字符替换多字符字符常量

python - 请在 Perl 或 Ruby 中引入多处理库

jQuery .get() 和 Perl 不能一起运行

regex - Perl 在字符串中用 "x"替换数字,但仅在一个特定位置

java - 为什么 char[] 优于 String 作为密码?

c# - 如何将 ListItemCollection (dropdownlist.items) 转换为字典<string,string>?

python - 在Python中比较pandas数据帧的单列值(将perl转换为python代码)