正则表达式匹配所有`,`不在\ [\]内 [英] regex match all `,` not inside \[\]

查看:101
本文介绍了正则表达式匹配所有`,`不在\ [\]内的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我必须匹配的示例字符串:

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屋!

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