欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

詳解python里使用正則表達式的分組命名方式

 更新時間:2017年10月24日 08:40:40   作者:caimouse  
這篇文章主要介紹了詳解python里使用正則表達式的分組命名方式的相關資料,希望通過本文能幫助到大家,需要的朋友可以參考下

詳解python里使用正則表達式的分組命名方式

分組匹配的模式,可以通過groups()來全部訪問匹配的元組,也可以通過group()函數(shù)來按分組方式來訪問,但是這里只能通過數(shù)字索引來訪問,如果某一天產(chǎn)品經(jīng)理需要修改需求,讓你在它們之中添加一個分組,這樣一來,就會導致匹配的數(shù)組的索引的變化,作為開發(fā)人員的你,必須得一行一行代碼地修改。因此聰明的開發(fā)人員又想到一個好方法,把這些分組進行命名,只需要對名稱進行訪問分組,不通過索引來訪問了,就可以避免這個問題。那么怎么樣來命名呢?可以采用(?P<name>pattern)的格式來命名。

例子如下:

#python 3.6 
#蔡軍生  
#http://blog.csdn.net/caimouse/article/details/51749579 
# 
import re 
 
text = 'This is some text -- with punctuation.' 
 
print(text) 
print() 
 
patterns = [ 
  r'^(?P<first_word>\w+)', 
  r'(?P<last_word>\w+)\S*$', 
  r'(?P<t_word>\bt\w+)\W+(?P<other_word>\w+)', 
  r'(?P<ends_with_t>\w+t)\b', 
] 
 
for pattern in patterns: 
  regex = re.compile(pattern) 
  match = regex.search(text) 
  print("'{}'".format(pattern)) 
  print(' ', match.groups()) 
  print(' ', match.groupdict()) 
  print() 



結(jié)果輸出如下:

This is some text -- with punctuation.

'^(?P<first_word>\w+)'
  ('This',)
  {'first_word': 'This'}

'(?P<last_word>\w+)\S*$'
  ('punctuation',)
  {'last_word': 'punctuation'}

'(?P<t_word>\bt\w+)\W+(?P<other_word>\w+)'
  ('text', 'with')
  {'t_word': 'text', 'other_word': 'with'}

'(?P<ends_with_t>\w+t)\b'
  ('text',)
  {'ends_with_t': 'text'}

如有疑問請留言或者到本站社區(qū)交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!

相關文章

最新評論