regular expression to get text between brackets that have text between brackets
php, regex
Solution
Yes you can use this pattern
v v
(\([^\)\(]*)+([^\)\(]*\))+
------------ -------------
| |
| |->match all (right)brackets to the right..
|
|->match all (left)brackets to the left
Demo
Above pattern won't work if you have a recursive pattern like this
(i want(to) (extract and also (this)) this text)
------
-------------------------
In this case you can use the recursive pattern as recommended by elclanrs
You can also do it without without using regex by maintaining a count of number of `(` and `)`
So, assume `noOfLB` is the count of `(` and `noOfRB` is the count of `)`
- keep on iterating each character in string and maintain the position of first `(`
- increament noOfLB if you find (
- increment noOfRB if you find )
- if noOfLB==noOfRB,you have found the last position of last `)`
I don't know php so I would implement above algo in c#
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 "";
}
Problem
After trying 10 times to rewrite this question to be accepted , i have a small text that have text between brackets, i want to extract that text so i wrote this expression : ``` /(\([^\)]+\))/i ``` but this only extracts text between first `(` and last `)` ignoring the rest of text so is there any way to extract full text like : ``` i want(to) extract this text ``` from : ``` this is the text that (i want(to) extract this text) from ``` there might be more than one bracket enclosed sub-text . Thanks EDIT Found this : ``` preg_match_all("/\((([^()]*|(?R))*)\)/", $rejoin, $matches); ``` very usefull from the link provided in the accepted answer