Ram Rachum
Ram Rachum

Reputation: 88528

Python: Getting text of a Regex match

I have a regex match object in Python. I want to get the text it matched. Say if the pattern is '1.3', and the search string is 'abc123xyz', I want to get '123'. How can I do that?

I know I can use match.string[match.start():match.end()], but I find that to be quite cumbersome (and in some cases wasteful) for such a basic query.

Is there a simpler way?

Upvotes: 7

Views: 268

Answers (2)

Martin Ender
Martin Ender

Reputation: 44259

You can simply use the match object's group function, like:

match = re.search(r"1.3", "abc123xyz")
if match:
    doSomethingWith(match.group(0))

to get the entire match. EDIT: as thg435 points out, you can also omit the 0 and just call match.group().

Addtional note: if your pattern contains parentheses, you can even get these submatches, by passing 1, 2 and so on to group().

Upvotes: 7

jpereira
jpereira

Reputation: 251

You need to put the regex inside "()" to be able to get that part

>>> var = 'abc123xyz'
>>> exp = re.compile(".*(1.3).*")
>>> exp.match(var)
<_sre.SRE_Match object at 0x691738>
>>> exp.match(var).groups()
('123',)
>>> exp.match(var).group(0)
'abc123xyz'
>>> exp.match(var).group(1)
'123'

or else it will not return anything:

>>> var = 'abc123xyz'
>>> exp = re.compile("1.3")
>>> print exp.match(var)
None

Upvotes: -1

Related Questions