egghead jr
egghead jr

Reputation: 111

python regex extract match object

This question has been asked before, but I'd like to re-ask it to provide another (perhaps more simple and to the point) example with a different spin.

Consider the following python regex and it's result.

import re

t = "The rain falls in Spain"
x = re.search("^The.*Spain$", t)

if x:
  print("There's a match!")
else:
  print("There's no match")

print (x)

Yields the following result:

There's a match!
<re.Match object; span=(0, 23), match='The rain falls in Spain'>

My question is simple.

How does one get the match object from the result?

Most of the other questions seem to address this topic in many different languages. The few on python seem to use compile, which I didn't quite grasp anyway, so I am wondering if there are other ways to do it? The simplest way is usually the best, I think.

Upvotes: 2

Views: 5022

Answers (1)

Wizard.Ritvik
Wizard.Ritvik

Reputation: 11642

Assuming you meant to find the phrase "The rain falls in Spain" within a larger string:

import re

t = "Hello G'day. The rain falls in Spain. Testing 123."
x = re.search("The.*Spain", t)

if x:
  print("There's a match!")
  print(f'The match is: {x.group(0)!r}')
  print('The span is:', x.span(0))
else:
  print("There's no match")

print(x)

Output:

There's a match!
The match is: 'The rain falls in Spain'
The span is: (13, 36)
<re.Match object; span=(13, 36), match='The rain falls in Spain'>

What did I change:

  • I removed ^$ from the regex, because we don't want to check for the start and end of a string explicitly. The desired match can also be somewhere within the string as well.
  • Access a captured group number n using the syntax x.group(n). In the above example, you can also use x.group() as a shortcut to get the first captured group (i.e. the first match)
  • Access the start/end indices within the input string, of a captured group n (i.e. a match), using the syntax x.span(n). Similarly as above, you can use x.span() as a shortcut to get the span of the first match.

Upvotes: 2

Related Questions