-1

Many python tutorials show a two line example of using re.

match=re.search('aa?yushi','ayushi')
match.group()

Is it recommended style to combine the two?

re.search('aa?yushi','ayushi').group()

I tried but it failed.

re.match('\d','a1b2c3d').group()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>

What's the trick?

Gert Gottschalk
  • 1,658
  • 3
  • 25
  • 37

2 Answers2

3

It's legal, but it's discouraged because there is no guarantee that the regex actually matches; when it doesn't match it returns None, and None has no .group method, so you get a less than helpful error message, as you've seen.

In your case, you accidentally triggered this by using re.match instead of re.search; re.match is implicitly anchored at the beginning of the string, so:

re.match('\d','a1b2c3d').group()

fails because the string being tested doesn't begin with a digit. By contest, it would work fine with re.search, which has no implicit anchoring:

re.search(r'\d','a1b2c3d').group()

Note: I used a raw string for the regex pattern, because you should always use raw strings for regexes; it works without it in this case, but only by accident, and only in Python (because Python makes the decision to treat unrecognized escapes as being literal backslashes; if your pattern had used \a, \b or many other escapes that have meaning both in str literals and regex, it wouldn't have worked).

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
  • I was following the explanation of match vs search as given in this page : https://www.geeksforgeeks.org/python-re-search-vs-re-match/ Their explanation is search is for multi-line string and match for first line or single line string. There is no mention of anchoring there. Though testing on the cmd line proves your statement. Is there a good tutorial pointer for the different incarnations of `re` pattern finding? – Gert Gottschalk Oct 29 '19 at 05:32
-1

Actually you can in python 3.7

enter image description here

Bill Chen
  • 1,699
  • 14
  • 24