包含符号的嵌套括号的正则表达式
我需要仅替换[用方括号]那些包含逗号的括号,无论它们位于哪个嵌套级别。
原始字符串的示例:
start (one, two, three(*)), some text (1,2,3), and (4, 5(*)), another
(four), interesting (five (6, 7)), text (six($)), here is (seven)
预期结果:
start [one, two, three(*)], some text [1,2,3], and [4, 5(*)], another
(four), interesting (five [6, 7]), text (six($)), here is (seven)
我能做的最好的事情就是不处理带有嵌套括号的部分:
preg_replace('~ \( ( [^()]+ (\([^,]+\))? , [^()]+ )+ \) ~x', ' [$1]', $string);
// start (one, two, three(*)), some text [1,2,3], and (4, 5(*)), another (four), interesting (five [6, 7]), text (six($)), here is (seven)
I need to replace [with square brackets] only those parentheses that contain comma, no matter on which nesting level they are.
Example of a raw string:
start (one, two, three(*)), some text (1,2,3), and (4, 5(*)), another
(four), interesting (five (6, 7)), text (six($)), here is (seven)
Expected result:
start [one, two, three(*)], some text [1,2,3], and [4, 5(*)], another
(four), interesting (five [6, 7]), text (six($)), here is (seven)
The best I could do doesn't cope with parts with nested parentheses:
preg_replace('~ \( ( [^()]+ (\([^,]+\))? , [^()]+ )+ \) ~x', ' [$1]', $string);
// start (one, two, three(*)), some text [1,2,3], and (4, 5(*)), another (four), interesting (five [6, 7]), text (six($)), here is (seven)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我会对输入进行标记,用逗号和括号将其分割,同时将这些分隔符保留为结果。然后使用递归算法检测某对括号是否出现逗号并进行适当的替换。
这是一个完成这项工作的函数:
I would tokenise the input, splitting it by commas and parentheses, keeping also these delimiters as results. Then use a recursive algorithm to detect whether commas appear for a certain pair of parentheses and make the appropriate replacement.
Here is a function doing the job:
好的,这不是正则表达式,但是,如果您找不到正则表达式,下一个算法就是您的 B 计划,大量注释(它可能对某人有用,这就是 StackOverflow 的用途):
编辑:已修复@trincot 发现的错误(谢谢)。
Ok, this is not regular expression, but, in case you don't find a regular expression, next alghoritm is your plan B, plenty of comments (it might be useful for someone, and that's what StackOverflow is for) :
Edit : fixed bug found by @trincot (thanks).