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