天天看點

第11.18節 Python 中re子產品的比對對象

比對對象是Python中re子產品正規表達式比對處理的傳回結果,用于存放比對的情況。老猿認為比對對象更多的應該是與組比對模式的功能對應的,隻是沒有使用組比對模式的正規表達式整體作為組0。

為了說明下面的屬性和方法,以如下命名組比對模式串和搜尋文本作為例子來介紹:

>>> pattern='<h1 class="name">(?P<name>.*)</h1><h1 class="age">(?P<age>[0-9]{1,3})</h1>'
>>> str='<h1 class="name">LaoYuanPython</h1><h1 class="age">28</h1>'
>>> m=re.search(pattern,str)

      

比對對象有如下重要屬性:

  1. re:該比對對象對應的正規表達式。如:
>>> m.re
re.compile('<h1 class="name">(?P<name>.*)</h1><h1 class="age">(?P<age>[0-9]{1,3})</h1>')
      
  1. string:該比對對象對應的搜尋字元串。如:
>>> m.string
'<h1 class="name">LaoYuanPython</h1><h1 class="age">28</h1>'
      
  1. lastgroup:最後一個比對組的名字,如果沒有比對到或沒有給組命名則為None。如:
>>> m.lastgroup
'age'
      
  1. lastindex:最後一個比對組的序号,關于組的序号請參考​​《第11.16節 Python正則元字元“()”(小括号)與組(group)比對模式》​​的介紹。如:
>>> m.lastindex
2
      

比對對象有如下重要方法:

  1. expand(template):對template的模闆字元串的反斜杠進行轉義并且傳回,數字引用(\1, \2)和命名組(\g<1>, \g) 替換為相應組的内容。
>>> m=re.search('(Lao)(\w+)(Python)','LaoYuanPython')
>>> m
<re.Match object; span=(0, 13), match='LaoYuanPython'>
>>> m.expand(r'\1\g<0>\2\n\r')
'LaoLaoYuanPythonYuan\n\r'
>>>
      

注意組0不能使用\0來通路,必須使用\g<0>進行通路。

2. start([group])、end([group]):表示比對到的組對應字元串在搜尋串中的起始位置和結束位置,其中group可以是組号或組名,可以不傳,則預設為組0。如:

>>> m.start(1),m.end(1)
(17, 30)
      
  1. group([group1, …]):顯示對應組比對的搜尋到的結果子串,參數可以為空,則顯示組0的比對結果串即整個搜尋串,也可以為多個組,組可以是組号或組名來表示。如:
>>> m.group(0,1,2)
('<h1 class="name">LaoYuanPython</h1><h1 class="age">28</h1>', 'LaoYuanPython', '28')
>>> m.group(0,1,'age')
('<h1 class="name">LaoYuanPython</h1><h1 class="age">28</h1>', 'LaoYuanPython', '28')
      
  1. groups(default=None):傳回一個元組,包含所有參與比對的子組(不含組0)。 default 參數用于未參與比對的子組顯示,預設為 None.
>>> m.groups()
('LaoYuanPython', '28')
關于未比對子組的情況,Python官網的如下例子可以說明:
>>> m = re.match(r"(\d+)\.?(\d+)?", "24")
>>> m.groups()      # Second group defaults to None.
('24', None)
>>> m.groups('0')   # Now, the second group defaults to '0'.
('24', '0')
      
  1. groupdict(default=None):傳回一個字典,包含了所有的 命名 子組(關于命名子組請參考《》的介紹)。key就是組名。 default 參數用于不參與比對的組合;預設為 None。 例如:
>>> m.groupdict()
{'name': 'LaoYuanPython', 'age': '28'}
      
  1. span([group]):傳回比對對象對應組比對到文本在搜尋文本中的起始和終止位置的元組,其結果與(m.start(group), m.end(group))相同 。 注意如果 參數group 沒有在這個比對中,就傳回 (-1, -1) 。group 預設為0,就是整個比對。
>>> m.span(1)
(17, 30)

      

案例:

>>> pattern='<h1 class="name">(?P<name>.*)</h1><h1 class="age">(?P<age>[0-9]{1,3})</h1>'
>>> str='<h1 class="name">LaoYuanPython</h1><h1 class="age">28</h1>'
>>> m=re.search(pattern,str)
>>> m.start('name'),m.end('name')
(17, 30)
>>> m.start(1),m.end(1)
(17, 30)
>>> m.string
'<h1 class="name">LaoYuanPython</h1><h1 class="age">28</h1>'
>>> m.re
re.compile('<h1 class="name">(?P<name>.*)</h1><h1 class="age">(?P<age>[0-9]{1,3})</h1>')
>>> m.lastgroup
'age'
>>> m.lastindex
2
      

​​老猿Python,跟老猿學Python!