Perl 拆分和正则表达式 [英] Perl split and regular expression

查看:65
本文介绍了Perl 拆分和正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下字符串:

'100% California Grown Olives, Water, Salt And Ferrous Gluconate (An,Iron, Derivative),asasd, sadasda'

我试图用 /,/ 分割它,但仅当它不在括号内,例如,在这种情况下,结果应该是:

I'm trying to split it by /,/ but only if its not inside brackets, for instance, in this case the result should be:

100% California Grown Olives
Water
Salt And Ferrous Gluconate (An,Iron, Derivative)
asasd
sadasda

谢谢,

推荐答案

@result = split(m/,(?![^()]*\))/, $subject);

仅当下一个括号(如果有)不是右括号时,才用逗号分隔.正如 Jack Maney 正确指出的那样,如果可能出现嵌套括号,这可能会导致失败.

This splits on a comma only if the next following parenthesis (if any) isn't a closing parenthesis. As Jack Maney noted correctly, this can lead to failure if nested parentheses may occur.

说明:

,       # Match a comma.
(?!     # Assert that it's impossible to match...
 [^()]* # any number of non-parenthesis characters
 \)     # followed by a closing parenthesis
)       # End of lookahead assertion

这篇关于Perl 拆分和正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆