0

可以从此类文档中获得:

/**
 * @mapping(table='example')
 */
class Example {

输出如下:

Array
(
  [table] => 'example'
)

等等,多个逗号分隔的参数,如@mapping(table='example', else=something,...) 使用正则表达式?

这实际上是我当前用于解析反射类文档内容的代码,该代码位于堆栈的某处。我对正则表达式不是那么强,感谢您的帮助!

function parseAnnotations($doc)
{

    preg_match_all('/@([a-z]+?)\s+(.*?)\n/i', $doc, $annotations);

    if(!isset($annotations[1]) OR count($annotations[1]) == 0){
        return [];
    }

    return array_combine(array_map("trim",$annotations[1]), array_map("trim",$annotations[2]));
}
4

1 回答 1

1

对于示例数据,您可以使用\G锚点来获得连续匹配。

(?:^/\*\*(?:\R\h+\*)*\R\h*\*\h*@mapping\(|\G(?!^)),?\h*([^\s=]+)=([^\s,=()]+)
  • (?:非捕获组
    • ^字符串的开始
    • /\*\*匹配**
    • (?:\R\h*\*)*可选择重复匹配换行符和*
    • \R\h*\*\h*@mapping\(匹配换行符、可选空格、*可选空格和@mapping
    • |或者
    • \G(?!^)在上一场比赛结束时断言位置,而不是在开始时
  • ),?关闭非捕获组并匹配可选逗号
  • \h*匹配可选的水平空白字符
  • ([^\s=]+)捕获组 1,匹配除=空格字符以外的任何字符 1 次以上
  • =从字面上匹配
  • ([^\s,=()]+)捕获组 2,匹配除列出的字符之一之外的任何字符 1 次以上

正则表达式演示

例子

$re = '~(?:^/\*\*(?:\R\h\*)*\R\h*\*\h*@mapping\(|\G(?!^)),?\h*([^\s=]+)=([^\s,=()]+)~m';
$str = '/**
 * @mapping(table=\'example\')
 */
class Example {


/**
 * @mapping(table2=\'example2\', else=something,...)
 */
class Example {';

preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);

foreach ($matches as $match) {
    echo sprintf("%s --> %s", $match[1], $match[2]) . PHP_EOL;
}

输出

table --> 'example'
table2 --> 'example2'
else --> something
于 2021-04-07T21:38:10.647 回答