开发者

Object propert is an integer, have to use regex to clean input, looking for good style

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, a开发者_如何学运维nd 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.


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))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜