Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple python regex, match after colon

Tags:

python

regex

I have a simple regex question that's driving me crazy. I have a variable x = "field1: XXXX field2: YYYY". I want to retrieve YYYY (note that this is an example value). My approach was as follows:

values = re.match('field2:\s(.*)', x)
print values.groups()

It's not matching anything. Can I get some help with this? Thanks!

like image 998
Ken Avatar asked Jun 07 '12 21:06

Ken


2 Answers

Your regex is good

field2:\s(.*)

Try this code

match = re.search(r"field2:\s(.*)", subject)
if match:
    result = match.group(1)
else:
    result = ""
like image 128
buckley Avatar answered Sep 28 '22 08:09

buckley


re.match() only matches at the start of the string. You want to use re.search() instead.

Also, you should use a verbatim string:

>>> values = re.search(r'field2:\s(.*)', x)
>>> print values.groups()
('YYYY',)
like image 42
Tim Pietzcker Avatar answered Sep 28 '22 07:09

Tim Pietzcker