Re: Simple Python REGEX Question
- From: Steven D'Aprano <steve@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx>
- Date: Sat, 12 May 2007 13:41:57 +1000
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.
.
- References:
- Simple Python REGEX Question
- From: johnny
- Simple Python REGEX Question
- Prev by Date: Re: stealth screen scraping with python?
- Next by Date: Re: Newbie question about string(passing by ref)
- Previous by thread: Re: Simple Python REGEX Question
- Next by thread: Re: Simple Python REGEX Question
- Index(es):
Relevant Pages
|