正则表达式匹配不在分组符号之间的逗号

发布于 2024-11-09 11:56:08 字数 447 浏览 3 评论 0原文

我需要一个正则表达式来匹配不在“[”和“]”或“(”和“)”或“{”和“}”之间的逗号。其他分组符号并不重要。我试图弄清楚这一点,但我想不出任何可以实现这一目标的方法。

正则表达式与 PHP preg_split 函数一起使用,以匹配的逗号分割字符串。

包含逗号和分组符号的示例字符串:

<div>Hello<div>,@func[opt1,opt2],{,test},blahblah

该字符串应拆分如下:

1: '<div>Hello<div>'
2: '@func[opt1,opt2]'
3: '{,test}'
4: 'blahblah'

我只是想到了这一点,但此时所有分组符号都保证具有匹配的符号,以防有帮助。

任何帮助将非常感激 =)

I need a regular expression that will match a comma that is NOT between either a '[' and ']' or '(' and ')' or '{' and '}'. Other grouping symbols do not matter. I have tried to figure it out but I cannot come up with anything that accomplishes this.

The regex is to be used with the PHP preg_split function to split a string on the matched commas.

An example string containing commas and grouping symbols:

<div>Hello<div>,@func[opt1,opt2],{,test},blahblah

The string should split up as follows:

1: '<div>Hello<div>'
2: '@func[opt1,opt2]'
3: '{,test}'
4: 'blahblah'

And I just thought of this, but at this point all grouping symbols are guaranteed to have matching symbols, incase that helps.

Any help would be GREATLY appriciated =)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

往事风中埋 2024-11-16 11:56:08

其实这种拆分也不是不可能的。考虑这段代码:

$str = '<div>Hello<div>,(foo,bar),@func[opt1,opt2],{,test},blahblah';
$arr = preg_split('~([^,]*(?:{[^}]*}|\([^)]*\)|\[[^]]*])[^,]*)+|,~', $str, -1 , PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
var_dump($arr);

输出:

array(5) {
  [0]=>
  string(15) "<div>Hello<div>"
  [1]=>
  string(9) "(foo,bar)"
  [2]=>
  string(16) "@func[opt1,opt2]"
  [3]=>
  string(7) "{,test}"
  [4]=>
  string(8) "blahblah"
}

Actually it is not impossible to get this splitting done. Consider this code:

$str = '<div>Hello<div>,(foo,bar),@func[opt1,opt2],{,test},blahblah';
$arr = preg_split('~([^,]*(?:{[^}]*}|\([^)]*\)|\[[^]]*])[^,]*)+|,~', $str, -1 , PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
var_dump($arr);

OUTPUT:

array(5) {
  [0]=>
  string(15) "<div>Hello<div>"
  [1]=>
  string(9) "(foo,bar)"
  [2]=>
  string(16) "@func[opt1,opt2]"
  [3]=>
  string(7) "{,test}"
  [4]=>
  string(8) "blahblah"
}
铁憨憨 2024-11-16 11:56:08

我认为不能用正则表达式来完成。基本问题是,这需要可变长度负向后查找(不允许任何 [({ 后面不跟 ])}),而这不是 RE 目前具备的功能。

I don't think it can be done in a regular expression. The basic problem is that this requires variable length negative look-behinds (disallow any [({ that is not followed by a ])}), and that isn't a capability which RE currently has.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文