正则表达式匹配逗号不在分组符号之间 [英] Regex to match comma not between grouping symbols

查看:75
本文介绍了正则表达式匹配逗号不在分组符号之间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个正则表达式来匹配不在["和]"或("和)"或{"和}"之间的逗号.其他分组符号无关紧要.我试图弄清楚,但我无法想出任何可以实现这一点的东西.

正则表达式将与 PHP preg_split 函数一起使用,以在匹配的逗号上拆分字符串.

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

你好

,@func[opt1,opt2],{,test},blahblah

字符串应拆分如下:

1: '

Hello

'2: '@func[opt1,opt2]'3: '{,test}'4:'blahblah'

我刚刚想到了这一点,但在这一点上,所有分组符号都保证具有匹配的符号,以防万一有帮助.

任何帮助都会非常有用=)

解决方案

实际上,完成这种拆分并非不可能.考虑以下代码:

$str = '

Hello

,(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) "

你好

"[1]=>string(9) "(foo,bar)"[2]=>string(16) "@func[opt1,opt2]"[3]=>字符串(7){,测试}"[4]=>字符串(8)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 =)

解决方案

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"
}

这篇关于正则表达式匹配逗号不在分组符号之间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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