正则表达式,用于在括号内包含文本的括号之间获取文本

Ron*_*ero 3 php regex

在尝试10次重写这个问题被接受后,我有一个小文本,括号之间有文本,我想提取该文本,所以我写了这个表达式:

/(\([^\)]+\))/i
Run Code Online (Sandbox Code Playgroud)

但是这只会在第一个(和最后一个之间提取文本而)忽略文本的其余部分,所以有没有办法提取全文,如:

i want(to) extract this text
Run Code Online (Sandbox Code Playgroud)

来自:

this is the text that (i want(to) extract this text) from
Run Code Online (Sandbox Code Playgroud)

可能有多个括号括起来的子文本.

谢谢

编辑 发现这个:

preg_match_all("/\((([^()]*|(?R))*)\)/", $rejoin, $matches);
Run Code Online (Sandbox Code Playgroud)

从接受的答案中提供的链接非常有用

Ani*_*dha 6

是的,你可以使用这种模式

   v                   v
 (\([^\)\(]*)+([^\)\(]*\))+
 ------------ -------------
      |            |
      |            |->match all (right)brackets to the right..
      |
      |->match all (left)brackets to the left
Run Code Online (Sandbox Code Playgroud)

演示


如果你有这样的递归模式,上面的模式将不起作用

(i want(to) (extract and also (this)) this text)
                              ------
            -------------------------
Run Code Online (Sandbox Code Playgroud)

在这种情况下,您可以使用elclanrs建议的递归模式


您也可以通过维护和的数量来使用正则表达式()

因此,假设noOfLB是计数,(并且noOfRB是计数)

  • 不断迭代每一个字符的字符串,保持位置第一 (
  • 如果找到,则增加noOfLB(
  • 如果你发现,增加noOfRB)
  • 如果noOfLB == noOfRB,你已经找到的最后一个位置最后 )

我不知道php所以我会在c#上面实现algo

public static string getFirstRecursivePattern(string input)
{
    int firstB=input.IndexOf("("),noOfLB=0,noOfRB=0;
    for(int i=firstB;i<input.Length && i>=0;i++)
    {
         if(input[i]=='(')noOfLB++;
         if(input[i]==')')noOfRB++;
         if(noOfLB==noOfRB)return input.Substring(firstB,i-firstB+1);
    }
    return "";
}
Run Code Online (Sandbox Code Playgroud)