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?
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With