首页 > 解决方案 > 提取带参数的函数调用

问题描述

我有一个翻译功能,想用正则表达式列出所有带有命名空间的翻译。

到目前为止,我想出的最好的事情是:

translate[\s]*\((?|'([^']*?(?:\\'|)[^']*?)'|"([^"]*?(?:\\"|)[^"]*?)")(?:|[, ]*(?:'|")(.*?)(?:"|'))\)

但是,([^']*?(?:\\'|)[^']*?)对于我的 regEx 技能来说,这部分太难了。有什么帮助吗?

找不到任何匹配排除序列的方法\'

translate('hello what\'s wrong');
translate('hello what\'s wrong');
translate('hello what\'s wrong');
translate("hello what's w: )rong");
translate("hello whats wrong");
translate('hello what\'s wrong');

translate('hello what\'s wrong', 'namespace');
translate('hell\'o what\'s wro\'ng', 'namespace');
translate("hello what\"s \" s\" wrong", 'namespace');
translate('hell(o) (wh)at\'s wrong', "namespace");
translate("hello what's wrong", "namespace");

translate  ('hello what\'s wrong');
translate("hel
lo what's wrong");

translate('hello what\'s wrong', 'namespace');
translate("hello wh
at's wrong", 'namespace');
translate('hello what\'s wrong', "namespace");
translate("hello what's wrong", "namespace");

translate[\s]*\((?|(?:')([^']*?(?:\\'|)[^']*?)(?:')|(?:")([^"]*?(?:\\"|)[^"]*?)(?:"))(?:|[, ]*(?:'|")(.*?)(?:"|'))\)

为了更容易调试什么不起作用https://regex101.com/r/8Jzso3/4

PS:我可能已经对所有这些组进行了过度复杂化。

标签: phpregexpcre

解决方案


要匹配所有测试字符串,我认为您需要做的就是*重复开始和结束之间的组''或者开始"和结束之间"的组(匹配非转义引号的组,最多单个转义\'\")。将重复组变成非捕获组,并在重复组周围使用另一个组来捕获参数字符串中外引号之间的所有内容。

您也可以简化translate[\s]*translate\s*,因为该字符集中只有一个字符。

translate\s*\((?|'((?:[^']*?(?:\\')[^']*?)*)'|"((?:[^"]*?(?:\\"|)[^"]*?)*)")(?:|[, ]*(?:'|")(.*?)(?:"|'))\)

https://regex101.com/r/8Jzso3/6


推荐阅读