正则表达式匹配所有`,`不在\ [\]内 [英] regex match all `,` not inside \[\]
问题描述
以下是我必须匹配的示例字符串:
Here is the example string which I have to match:
var sampleStr = "aaa[bbb=55,zzz=ddd],#ddd[ppp=33,kk=77,rr=fff],tt,ff";
我需要编写匹配所有的正则表达式,
不在内的字符[
]
I need to write regex that will match all ,
characters which is not inside [
]
所以在我的示例字符串中,我应该收到下一个,
字符:
so In my sample string I should receive the next ,
characters:
- `,` before `#ddd`
- `,` before `tt`
- `,` before `ff`
它应该忽略下一个,
:
- `,` before `zzz`
- `,` before `kk`
- `,` before `rr`
其实我不知道如何忽略里面的那些
。 ,
[.. ]
任何提前的大thx
Actually I have no idea how to ignore those ,
inside [...]
.
Big thx for any advance
推荐答案
如果你可以假设 []内的部分
不包含嵌套的 []
,并且 []
是平衡的:
If you can assume that the part inside []
doesn't contain nested []
, and the []
are balanced:
var out = content.split(/,(?![^\[\]]*\])/);
(?![^ \ [\]] * \ ])
是一个负向前瞻,用启发式方法检查我们是否在 []
内。只要我们没有遇到任何]
,因为我们使用的字符不是 [
和 ]
,然后我们在 []
之外。
(?![^\[\]]*\])
is a negative look-ahead which checks that we are not inside []
with a heuristic. As long as we don't encounter any ]
as we consume characters other than [
and ]
, then we are outside []
.
上面的代码将拆分这些逗号上的文字,
在括号 []
之外并返回令牌。
The code above will split the text along those commas ,
outside brackets []
and return the tokens.
这篇关于正则表达式匹配所有`,`不在\ [\]内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!