arrays - split string (based on comma) into array adds an empty item at the end of list
问题描述
I'm using below regex to split a string in the basis of comma into array, which works completely fine.
my $string = '$n(bar,foo), (bar),a.*$n(f04((?!z).)*)b,
hello$n(((((((abcdef)))))))world';
my @array;
push @array, $1 while $string =~ /
((?:
[^(),]+ |
( \(
(?: [^()]+ | (?2) )*
\) )
)*)
(?: ,\s* | $)
/xg;
$VAR1 = [
'$n(bar,foo)',
'(bar)',
'a.*$n(f04((?!z).)*)b',
'hello$n(((((((abcdef)))))))world',
''
];
Problem is it always adds an empty string as the last item of an array. I don't want this. Please help.
解决方案
Your first capturing group contains a *
-quantified non-capturing group, and thus can be empty. To avoid that, you need to use a +
quantifier to make it match at least once.
push @array, $1 while $string =~ /
((?:
[^(),]+ |
( \(
(?: [^()]+ | (?2) )*
\) )
)+) # < HERE
(?: ,\s* | $)
/xg;
推荐阅读
- python - Django Modelform - 它没有验证,为什么?
- vb.net - 在 winform 中运行 Async/Await 代码时,它会阻止 Winform UI,但在控制台模式下运行时可以工作
- r - 检查值列表是否在范围列表内(逐类)
- go - 打印结构数组只打印指针值
- python - Python 从委托账户发送电子邮件
- java - 按对象的属性对地图进行排序
- html - 如何修复引导程序不透明度?
- c++ - 我可以 automoc 继承 QObject 的仅标头对象吗?
- java - JFoenix 库中日期字段的 JFXTreeTableColumn 问题
- wiremock - 可以将wiremock json存根设置为在命中端点时运行我自己的脚本吗?