渴望量词之前的负向后看

时间:2020-04-23 13:20:11

标签: php regex pcre

我需要重构一些PHP注释,我想将string[]替换为array<int, string>

我尝试将适当的注释与此PCRE正则表达式进行匹配:

(?<!\$|>)\w+\[\]

但这不起作用,here's how the regex is matching

Regex 101 preview

最新的两行不应匹配。有什么方法可以为此创建有效的正则表达式,还是应该使用创建自定义脚本来做到这一点?

1 个答案:

答案 0 :(得分:1)

您可以使用

\b(?<!\$|->)\w+\[]

请参见PCRE regex demo

详细信息

  • \b-单词边界
  • (?<!\$|->)-如果在当前位置的左侧紧跟着$->,则反向查找将使匹配失败
  • \w+-1个以上的字符字符。
  • \[]-一个[]子字符串。

请参见PHP demo

$str = '/** @var string[] */
/** @return string[] */
* @param Company[]|null $companies

$icons[] = static::getIconDetailsFromLink($link);
$this->properties[] = $property;';

if (preg_match_all('/\b(?<!\$|->)\w+\[]/', $str, $matches)) {
  print_r($matches);
}
相关问题