函数调用的正则表达式?

时间:2011-06-13 18:11:08

标签: php regex

我希望简单地从函数调用中提取一些引用的文本,并且想知道我是否可以获得一些正则表达式的帮助?

字符串看起来像这样: 'MyFunction的( “MyStringArg”);'

实际上,我想扫描文件中是否有任何调用'MyFunction'的行,然后在引号内捕获字符串文字。

后续问题
我将如何避免使用此注释线?

更新
我能够解决我的问题:
MyFunction\s*\(\s*"(.*?)\"\s*\)\s*;

感谢@devyndraen和大家的帮助!

4 个答案:

答案 0 :(得分:2)

我不确定你对格式化有什么样的要求,所以我假设在正常的编程场所可能存在任何数量的空间。

结果字符串将位于\ 1反向引用中。

MyFunction\s*\(\s*"(.*?)\"\s*\)\s*;

http://rubular.com/r/qVsaqJS6gJ

答案 1 :(得分:1)

我建议这个非贪婪的正则表达式使用标志s(Java中的DOTALL)(假设此函数调用的括号内没有注释:

$regex = '/MyFunction.*?\(.*?"(.*?)".*?\).*?;/s';

如果您使用preg_match($regex, $str, $matches),则参数将在$matches[1]中提供。

答案 2 :(得分:0)

要补偿注释的行或块,首先需要在应用正则表达式之前过滤文件以删除所有注释。对于PHP,您可以使用以下内容:



$example='
line 1
line 2 // comment 1
line 3 # comment 2
// comment 3.1
# comment 3.2
/*
   comment 4.1
   comment 4.2
*/
line 9 /* comment 5.1
comment 5.2
*/';

echo '<h3>Example Text</h3><pre>'.$example.'</pre><hr>';

$regex='/
    (?x)
    (?:
        # single-line inline comments beginning at col#1
        (?s)
        (?:\\/\\/|\\#)
        [^\\n]+
        \\n
    |
        # single-line inline comments beginning after col#1 
        # preserve leading content
        (?m)
        ^
        (.+?)
        (?:\\/\\/|\\#)
        .*?
        $
    |
        # multi-line comments
        (?s)
        \\/
        \\*
            (?:.|\\n)*?
        \\*
        \\/
    )
/x';

echo '<h3>Regular Expression</h3><pre>'.$regex.'</pre><hr>';

$result=preg_replace( $regex, '$1', $example);

echo '<h3>Result</h3><pre>'.$result.'</pre><hr>';

产生:


示例文本

line 1
line 2 // comment 1
line 3 # comment 2
// comment 3.1
# comment 3.2
/*
   comment 4.1
   comment 4.2
*/
line 9 /* comment 5.1
comment 5.2
*/

正则表达式

/
    (?x)
    (?:
        # single-line inline comments beginning at col#1
        (?s)
        (?:\/\/|\#)
        [^\n]+
        \n
    |
        # single-line inline comments beginning after col#1 
        # preserve leading content
        (?m)
        ^
        (.+?)
        (?:\/\/|\#)
        .*?
        $
    |
        # multi-line comments
        (?s)
        \/
        \*
            (?:.|\n)*?
        \*
        \/
    )
/x

结果

line 1
line 2 
line 3 

line 9

答案 3 :(得分:-1)

[^(]*("([^"]*)")

然后组号1将是引号中的字符串。你必须自己再次引用它。

(这不是很科学,因为它可能会收集一些你不想要的东西)