简体   繁体   English

正则表达式匹配group(0)和group()是否相同?

[英]Are regular expression match group(0) & group() the same?

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) ? 在上面的代码中,组m.match(a).group()的整个匹配项是否与m.match(a).group() 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). 没有参数, group1默认为零(返回整个匹配项)。

So, yes; 所以,是的; .group() gives the same result as .group(0) . .group().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. 因为在这种情况下进行编译几乎没有好处。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM