extracting a pattern using RE

Justin Sheehy justin at iago.org
Thu Nov 29 21:40:19 EST 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()[0]
>>> res
'hello'

> 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
straightforward.

-Justin

 






More information about the Python-list mailing list