Simple Python REGEX Question

Steven D'Aprano steve at REMOVE.THIS.cybersource.com.au
Fri May 11 23:41:57 EDT 2007


On Fri, 11 May 2007 08:54:31 -0700, 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?

Why would you bother? If you know your string is a bracketed expression,
all you need is:

s = "(3.12345)"
contents = s[1:-1] # ignore the first and last characters

If your string is more complex:

s = "lots of things here (3.12345) and some more things here"

then the task is harder. In general, you can't use regular expressions for
that, you need a proper parser, because brackets can be nested.

But if you don't care about nested brackets, then something like this is
easy:

def get_bracket(s):
    p, q = s.find('('), s.find(')')
    if p == -1 or q == -1: raise ValueError("Missing bracket")
    if p > q: raise ValueError("Close bracket before open bracket")
    return s[p+1:q-1]

Or as a one liner with no error checking:

s[s.find('(')+1:s.find(')'-1]


-- 
Steven.




More information about the Python-list mailing list