簡體   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

在上面的代碼中,組m.match(a).group()的整個匹配項是否與m.match(a).group() m.match(a).group(0) 如果是這樣,哪個是首選用途?

根據文檔

沒有參數, group1默認為零(返回整個匹配項)。

所以,是的; .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:
  ...

甚至只是:

...
g = re.match(r"([A-Z]{2})(\s?_?\s?)([0-9]{2})", a)
if g:
    ...

因為在這種情況下進行編譯幾乎沒有好處。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM