如何在忽略括号的部分时拆分字符串? [英] How to split string while ignoring portion in parentheses?
本文介绍了如何在忽略括号的部分时拆分字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个字符串,我想通过使用逗号作为分隔符将其拆分为一个数组.我不希望括号中的字符串部分被分割,即使它们包含逗号也是如此.
I have a string that I want to split into an array by using the commas as delimiters. I do not want the portions of the string that is between parentheses to be split though even if they contain commas.
例如:
"bibendum, morbi, non, quam (nec, dui, luctus), rutrum, nulla"
应成为:
["bibendum", "morbi", "non", "quam (nec, dui, luctus)", "rutrum", "nulla"]
但是当我使用基本的 .split(,")
时,它将返回:
But when I use a basic .split(",")
, it returns:
["bibendum", " morbi", " non", " quam (nec", " dui", " luctus)", " rutrum", " nulla"]
我需要它返回:
["bibendum", " morbi", " non", " quam (nec, dui, luctus)", " rutrum", " nulla"]
我们非常感谢您的帮助.
Your help is appreciated.
推荐答案
与其专注于您不想要的,通常更容易将正则表达式表达为想要的,并 match 代码>
,并带有全局正则表达式:
Instead of focusing on what you do not want it's often easier to express as a regular expression what you want, and to match
that with a global regex:
var str = "bibendum, morbi, non, quam (nec, dui, luctus), rutrum, nulla";
str.match(/[^,]+(?:\(+*?\))?/g) // the simple one
str.match(/[^,\s]+(?:\s+\([^)]*\))?/g) // not matching whitespaces
这篇关于如何在忽略括号的部分时拆分字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文