extracting a pattern using RE
justin at iago.org
Fri Nov 30 03:40:19 CET 2001
"Peoter Veliki" <peoter_veliki at hotmail.com> writes:
> In perl you can use variables within regular expressions to extract
> patterns, something like this:
> string ~= /\((.*)\)/g
> pattern = $1
> Probably not correct, but it is attempting to extract text
> surrounded by parenthes
> if string equals '(hello)', pattern would equal 'hello'. How can
> this be done in Python?
>>> matchobj = re.search('\((.*)\)', '(hello)')
>>> res = matchobj.groups()
> I also am having problems with recursive patterns, what if I want to
> do the same thing with string = '(hello (there))' , I want to be
> able to extract both 'hello (there)' and 'there'.
Since regular expressions can't count, they aren't so handy when
trying to analyze nested structure.
However, if your only need is extracting from parentheses, writing a
little parser that would return the strings you want would be quite
More information about the Python-list