【问题标题】:regexp: how to postprocess replace result正则表达式:如何后处理替换结果
【发布时间】:2015-01-15 08:22:58
【问题描述】:

在我的文本编辑器(phpStorm、notepad++、jedit 等)中,我有如下字符串:

....    $this->request_json['store-user-id'] .....
....    $this->request_json['deviceID'] ....

我需要将它们替换为:

$this->request->store_user_id
$this->request->device_id

search: \-\>request_json\[\"([\w_\-]+)\"\]
replace: ->request->$1

但是:我需要额外的内联替换“-”->“_”,转换为小写并在每个大写字母前加上“_”。

这可能使用 perl 风格的正则表达式吗?也许是递归的?

【问题讨论】:

  • 在 Notepad++ 6.0 或更高版本中,您可以使用“PCRE(Perl 兼容正则表达式)搜索/替换”(来源:sourceforge.net/apps/mediawiki/notepad-plus/…)。所以你可以使用像(. )([A-z])(.+)这样的正则表达式和像\1\U\2\3这样的替换参数
  • 谢谢。我在哪里可以找到有关这些有趣的替换参数的信息? notepad++ 帮助中没有任何内容
  • 请查看此链接:letconex.blogspot.fr/2013/06/…。见9. Substitutions

标签: php regex notepad++ phpstorm jedit


【解决方案1】:

只需在 $txt 字符串上应用这 4 次连续的正则表达式替换

$txt =~ s/_json\[\'/->/;
$txt =~ s/']//;
$txt =~ s/([a-z])([A-Z])/\1_\2/g;
$txt =~ tr/[A-Z]/[a-z]/;

【讨论】:

  • 我使用大型 php 文档,因此只能在找到的子模式中进行替换。我搜索“后处理”正则表达式结果的方式。我现在看到的唯一方法是通过 preg_match_all 提取所有找到的字符串,然后使用 preg_replace、str_replace 和 strtolower 处理它们。
【解决方案2】:

终于解决了php中的问题:

$fstr = implode("", file("file_with_text_to_replace.php"));
$rfstr = preg_replace_callback("/\\-\\>request_json\\[(?:\\\"|\\')([\\w_\\-]+)(?:\\\"|\\')\\]/",
             function ($matches)
             {
               //any post-processing
               return  "->request->" . str_replace("-","_", $matches[1]);
             },
             $fstr);

这是最强大的解决方案。这些天我对php有点失去联系,但我很惊讶没有人指出这个php函数。它可以完全控制搜索结果,这在文本编辑器中是不可能的。太棒了!

【讨论】:

  • 你转义的字符太多,->' 不需要转义,\w 已经包含了-,单个反斜杠足以转义"[]。你的正则表达式会变得更具可读性。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-09-02
  • 2017-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-23
相关资源
最近更新 更多