Simple Python REGEX Question

John Machin sjmachin at lexicon.net
Fri May 11 20:23:12 EDT 2007


On May 12, 2:21 am, Gary Herron <gher... at islandtraining.com> wrote:
> johnny wrote:
> > I need to get the content inside the bracket.
>
> > eg. some characters before bracket (3.12345).
>
> > I need to get whatever inside the (), in this case 3.12345.
>
> > How do you do this with python regular expression?
>
> >>> import re
> >>> x = re.search("[0-9.]+", "(3.12345)")
> >>> print x.group(0)
>
> 3.12345
>
> There's a lot more to the re module, of course.  I'd suggest reading the
> manual, but this should get you started.
>

>>> s = "some chars like 987 before the bracket (3.12345) etc"
>>> x = re.search("[0-9.]+", s)
>>> x.group(0)
'987'

OP sez: "I need to get the content inside the bracket"
OP sez: "I need to get whatever inside the ()"

My interpretation:

>>> for s in ['foo(123)bar', 'foo(123))bar', 'foo()bar', 'foobar']:
...     x = re.search(r"\([^)]*\)", s)
...     print repr(x and x.group(0)[1:-1])
...
'123'
'123'
''
None







More information about the Python-list mailing list