正则表达式:表达式选择超出预期

时间:2017-10-28 14:17:08

标签: php regex

我正在使用以下正则表达式

'/\@(.*)\((.*)\)/'

我正试图从表达式中获得一个和两个@ONE(TWO)。哪个有效,只要它是唯一一次可以在行尾之前找到它(我认为)

我对正则表达式非常环保,我真的无法理解我做错了什么。

我需要的是能够获得所有一对/两对夫妇。你能帮我么。

我正在使用PHP和以下函数

$parsed_string = preg_replace_callback(
    // Placeholder for not previously created article
    // Pattern example: @George Ioannidis(person)             
    '/\@(.*)\((.*)\)/', 
    function ($matches) {
        return $this->parsePlaceholders( $matches );
    },
    $string
);

我从https://regexr.com 获得的结果 The results I am getting from https://regexr.com/

1 个答案:

答案 0 :(得分:1)

默认情况下,

*表达式是贪婪的。例如,此类正则表达式(.*)a会在bdeabde字符串上返回bdeabdea个结果。您应该使用特殊的?符号来表示非贪婪的*行为。在您的情况下,尝试使用/\@(.*?)\((.*?)\)/ regexp。