7

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?

3
  • re.finditer() Commented Apr 25, 2013 at 14:48
  • 1
    @Elazar judging by the question, the OP knows how to obtain MatchObjects, but not how to easily get their contents. Commented Apr 25, 2013 at 14:54
  • Does this answer your question? How to get only the matched text in Python? Commented Sep 15, 2022 at 8:15

2 Answers 2

7

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

Sign up to request clarification or add additional context in comments.

3 Comments

Unintuitive in my opinion... But I guess that's the best that Python provides.
@RamRachum I don't think it's too odd. When you do regex replacements you refer to the capturing groups with \1, \2 and so on (or $1, $2, depending on implementation), and the entire match is often referred to by using \0 (or $0). So it's consistent with that numbering of groups.
You can omit 0, just match.group().
-1

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

1 Comment

I don't think using .*(...).* for substring matches is a good practice. Just use search instead of match and it does all the for you. In fact, it's even superior, as you won't be able to get multiple matches with match (instead it will return the last one, which is also quite intuitive, as opposed to the first one).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.