【问题标题】:What is the regex to find and replace commas not surrounded by curly braces with commas surrounded by curly braces using preg_replace? [duplicate]什么是使用 preg_replace 查找和替换没有被花括号包围的逗号和被花括号包围的逗号的正则表达式? [复制]
【发布时间】:2012-11-05 17:05:11
【问题描述】:

可能重复:
Regex to match comma not between grouping symbols

使用 preg_replace 查找和替换两边没有被大括号包围的逗号和两边都被大括号包围的逗号的正则表达式是什么?

例子:

$subject = "blah.blah,{blah.blah},blah.blah";

$result = "{blah.blah},{blah.blah},{blah.blah}";

避免这种和其他不需要的变化:

$result = "{blah.blah},{{blah.blah}},{blah.blah}";

【问题讨论】:

  • @Asad 什么? preg_replace 找不到替换?
  • @mario 我的问题有些相似,但与您提到的问题不完全相同
  • 抱歉重复了上一个问题,但也感谢您的回答。

标签: php regex


【解决方案1】:
preg_replace("/(?<=^|,)([^{},]+)(?=$|,)/", '{$1}', "blah.blah,{blah.blah},blah.blah");

【讨论】:

  • {$1} 上使用撇号而不是双引号,否则可能会返回解析错误。
  • @FabrícioMatté 好的,谢谢。
【解决方案2】:

答案有效,但有一个更好的正则表达式,因为后视和后视对机器来说太贵了:

preg_replace('/(^|,)([^{},]+)($|,)/', '$1{$2}$3', 'blah.blah,{blah.blah},blah.blah');

【讨论】:

  • 我也试过这个,它适用于我提供的示例字符串。感谢您让我知道后视和后视的昂贵性。
猜你喜欢
  • 1970-01-01
  • 2016-04-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-05
  • 1970-01-01
  • 2020-07-03
  • 1970-01-01
相关资源
最近更新 更多