【问题标题】:How to get method/function in a string by using regex如何使用正则表达式获取字符串中的方法/函数
【发布时间】:2020-03-12 03:13:57
【问题描述】:

我试图从字符串中的函数获取参数。

参数可能包含:

示例

占位符:

{{request.expires_in}}
//can match regex: \{\{[a-zA-z0-9\.\-\_]\}\}

功能

@func_compare('string1','string2',1234)

其他:

dERzUxOfnj49g/kCGLR3vhzBOTLwEMgrpa1/MCBpXQR2NIFV1yjraGVZLkujG63J0joj+TvNocjpJSQq2TpPRzLfCSZADcjmbkBkphIpsT8=
//Any string except brackets

案例

以下是我使用的示例案例。

内容:

@func_compare('string1',@func_test(2),1234),'Y-m-d H:i:s',@func_strtotime({{request.expires_in}} - 300)

正则表达式使用:

(?<=@func_compare\().*[^\(](?=\))

我希望得到

'string1',@func_test(2),1234

但是现在从正则表达式匹配的是

'string1',@func_test(2),1234),'Y-m-d H:i:s',@func_strtotime({{request.expires_in}} - 300

任何人都知道如何在@func_strtotime 括号之间获取参数。我将不胜感激。

【问题讨论】:

  • @CarySwoveland 更新了我的问题。

标签: regex pcre


【解决方案1】:

您将使用递归正则表达式获得结果:

(?<=@func_compare\()([^()]*\((?:.*?\)|(?1))*)[^()]*(?=\))

Demo & explanation

【讨论】:

    【解决方案2】:

    请你试试:

    (?<=@func_compare\().*?(?:\(.*?\).*?)?(?=\))
    

    这两种情况都适用。

    [正则表达式的解释]

    .*?(?:\(.*?\).*?)?(?=\))
    
    .*?                       the shortest match not to overrun the next pattern
       (?:\(.*?\).*?)?        a group of substring which includes a pair of parens followed by another substring of length 0 or longer
                      (?=\))  positive lookahead for the right paren
    

    【讨论】:

    • 感谢您的回答。正则表达式无法获得预期的匹配结果
    • @Deno 感谢您的反馈。您是否需要一个统一的正则表达式,它既适用于先前的字符串,也适用于新的字符串?或者只为新的解决方案是可以接受的?
    • 是的,需要同时处理旧字符串和新字符串。我在答案示例部分中列出的可能匹配字符串。
    • 感谢您的及时回复。我已经相应地更新了我的答案。请你测试一下好吗? BR。
    • 再次感谢您的回复。你的答案几乎完美。只是无法涵盖 @func_compare('str',@func_test('1',@func_test('2')),'str',@func_test('3')) 和 @func_compare('str', @func_test('1',@func_test('2')),'str') 我认为我的问题无法仅使用正则表达式来解决。无论如何,感谢您的耐心和善意的帮助。
    猜你喜欢
    • 2012-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    相关资源
    最近更新 更多