Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Getting text of a Regex match

Tags:

python

regex

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?

like image 277
Ram Rachum Avatar asked Apr 25 '13 14:04

Ram Rachum


1 Answers

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().

like image 103
Martin Ender Avatar answered Sep 29 '22 10:09

Martin Ender