【问题标题】:get all text between bracket but skip nested bracket获取括号之间的所有文本但跳过嵌套括号
【发布时间】:2019-03-21 14:45:30
【问题描述】:

我试图弄清楚如何在两个括号标签之间获取文本,但不要在第一次关闭时停止)

__('This is a (TEST) all of this i want') i dont want any of this;

我目前的模式是__\((.*?)\)

这给了我

__('This is a (TEST) 

但我想要

__('This is a (TEST) all of this i want') 

谢谢

【问题讨论】:

    标签: php regex regex-negation


    【解决方案1】:

    您可以使用正则表达式子例程来匹配 __ 之后嵌套括号内的文本:

    if (preg_match_all('~__(\(((?:[^()]++|(?1))*)\))~', $s, $matches)) {
        print_r($matches[2]);
    }
    

    请参阅regex demo。

    详情

    • __ - __ 子字符串
    • (\(((?:[^()]++|(?1))*)\)) - 第 1 组(将使用 (?1) 子例程进行递归):
      • \( - 一个 ( 字符
      • ((?:[^()]++|(?1))*) - 第 2 组捕获除 ( 和 ) 或整个第 1 组模式之外的任何 1+ 字符的 0 次或多次重复
      • \) - ) 字符。

    见PHP demo:

    $s = "__('This is a (TEST) all of this i want') i dont want any of this; __(extract this)";
    if (preg_match_all('~__(\(((?:[^()]++|(?1))*)\))~', $s, $matches)) {
        print_r($matches[2]);
    }
    // => Array ( [0] => 'This is a (TEST) all of this i want'  [1] => extract this )
    

    【讨论】:

      【解决方案2】:

      您忘记在正则表达式中转义两个括号:__\((.*)\);

      检查regex101.com。

      【讨论】:

        【解决方案3】:

        使用模式__\((.*)?\)。

        \ 转义括号以捕获文字括号。然后,这会捕获该组括号内的所有文本。

        【讨论】:

          猜你喜欢
          • 2019-03-18
          • 2013-11-10
          • 1970-01-01
          • 1970-01-01
          • 2013-04-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-10-24
          相关资源
          最近更新 更多