Perl 用“and”分割逗号分隔的列表
使用Perl,我想在逗号和“and”上分割
一个字符串(前面可能有也可能没有逗号。
“Apple”
给出数组< code>(Apple)"Apple and Orange"
给出数组(Apple Orange)
"Apple, Orange, and Banana"
给出array(Apple Orange Banana)
由于某种原因以下分割正则表达式对我不起作用:
split(/(,| and )/, $string)
Using Perl, I would like to split
a string on the comma and the "and" (that may or may not be preceded by a comma.
"Apple"
gives array(Apple)
"Apple and Orange"
gives array(Apple Orange)
"Apple, Orange, and Banana"
gives array(Apple Orange Banana)
For some reason the following split regex is not working for me:
split(/(,| and )/, $string)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
试试这个:
示例:
或者为您的示例提供一个更简单的工作案例:
Try this:
Example:
Or a simpler working case for your example:
以下
split
应该适合您:The following
split
should work for you:这是一种解决方案。它依赖于两个
split
来完成所有繁重的工作,并使用map
来方便起见。它可能与其他答案没有太大不同,但它很干净,而且很容易看清(除了打印之外)。我认为它适用于空格/和/逗号的大多数变体。输出:
Here's one solution. It relies on two
split
doing all the heavy lifting, with amap
for convenience. It's probably not very different from the other answers, but it's clean, and it's fairly easy on the eyes (except maybe for the print). And I think it will work with most variations on whitespace/and/comma.Output: