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?

1 Answers

1
jonrsharpe On

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.