正则表达式match group(0)&group()是否相同?

2024-10-16 22:25:15 发布

您现在位置:Python中文网/ 问答频道 /正文

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

在上面的代码中,组m.match(a).group()的整个匹配是否与m.match(a).group(0)相同?如果是的话,哪个是首选的用途?在


Tags: 代码importresearchstringrawifmatch
1条回答
网友
1楼 · 发布于 2024-10-16 22:25:15

根据the documentation

Without arguments, group1 defaults to zero (the whole match is returned).

所以,是的;.group()给出了与.group(0)相同的结果。在


请注意,您正在测试编译的正则表达式的真实性,而不是它是否匹配,这看起来很奇怪。也许你的意思是:

a = "AB01"
m = re.compile(r"([A-Z]{2})(\s?_?\s?)([0-9]{2})")  # note raw string
g = m.match(a)
if g:
  ...

或者只是:

^{pr2}$

因为在这种情况下编译没有什么好处。在

相关问题 更多 >