Ken
Ken

Reputation: 560

Simple python regex, match after colon

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!

Upvotes: 7

Views: 35828

Answers (2)

Tim Pietzcker
Tim Pietzcker

Reputation: 336408

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',)

Upvotes: 9

buckley
buckley

Reputation: 14109

Your regex is good

field2:\s(.*)

Try this code

match = re.search(r"field2:\s(.*)", subject)
if match:
    result = match.group(1)
else:
    result = ""

Upvotes: 15

Related Questions