import re
a = "AB01"
m = re.compile(r"([A-Z]{2})(\s?_?\s?)([0-9]{2})") # note raw string
g = m.match(a)
if g:
g = m.match(a).group(1) + "-" + m.search(a).group(3)
print m.match(a).group()
print m.match(a).group(0)
print (m.match(a).group(0) == m.match(a).group())
print g
In the above code, is the whole match of the group m.match(a).group()
, is that the same as m.match(a).group(0)
? If so, which is the preferred use?
Per the documentation :
Without arguments, group1 defaults to zero (the whole match is returned).
So, yes; .group()
gives the same result as .group(0)
.
Note that you're testing the truthiness of the compiled regex, not whether or not it has matched, which seems weird. Perhaps you meant:
a = "AB01"
m = re.compile(r"([A-Z]{2})(\s?_?\s?)([0-9]{2})") # note raw string
g = m.match(a)
if g:
...
or even just:
...
g = re.match(r"([A-Z]{2})(\s?_?\s?)([0-9]{2})", a)
if g:
...
as there's very little benefit to compiling in this situation.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.