tags:

views:

24

answers:

1

I have some text that looks like:

California(2342)

My object has a property that I need to assign the value 2342 to.

I'm looking for input on how to go about doing this, and guarding against any potential for errors in the input.

c = SomeClass()

c.count = re.compile(r'(\d*)').groups[0]

Does that look ok? Or should I do an IF statement and set the count to 0 in case the input was bad?

P.S any help in the regex would be appreciated, this is my first serious python script.

+2  A: 
import re

pat = re.compile(r'\w+\((\d+)\)')

s = 'California(2342)'
match = pat.match(s)
if match:
    c.count = match.group(1)
    print c.count
    # '2342'
else:
    c.count = '0'  # or 0 if numeric

If you want a number back instead of a string just modify:

value = int(match.group(1))
ars
should I do: if match and match.groups() > 0 ?
Blankman
+1 +nitpick: change that final line to `c.count = '0'` for type consistency.
msw
Not necessary to do that because the match will be None if no group is found. Because the regex requires \d+, i.e. one or more digits. So if there aren't any digits, then the match will fail. You would have to test for it though if it was optional, i.e. something like \d* (*zero* or more digits).
ars
@msw: good point!
ars