Re: Simple Python REGEX Question



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.

.



Relevant Pages

  • Re: How to form a dict out of a string by doing regex ?
    ... , POLYGON ... This is my string. ... # regex is not good with nested brackets, ... # so kill off outer nested brackets.. ...
    (comp.lang.python)
  • Re: Find spaces with Regex
    ... working fine, except in the example "1 space", it is picking up the space. ... I know it's because it's looking for a space, &, n, b, s, p,; character. ... How to I change the regular expression to look for a space ... without a quantifier like the * I added would only match a single one of the characters in the brackets. ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: need help on regular expression pattern
    ... You need to spell out your rules more clearly. ... The most important step to writing a good regular expression is to clearly ... can have brackets. ... of the character class. ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Effective use of the ^& find/replace wildcard
    ... Put (brackets) around parts you want to re-use. ... The paragraph mark ^13 gets deleted. ... > and replace them with a space character. ... > space since it appears in the regular expression. ...
    (microsoft.public.word.docmanagement)
  • splitting words with brackets
    ... I've got some strings to split. ... are inside a pair of brackets and should be considered as one unit. ... regular expression can handle this. ... Any hint? ...
    (comp.lang.python)