詳解python/142942.html">python里使用正則表達式的分組命名方式
分組匹配的模式,可以通過groups()來全部訪問匹配的元組,也可以通過group()函數來按分組方式來訪問,但是這里只能通過數字索引來訪問,如果某一天產品經理需要修改需求,讓你在它們之中添加一個分組,這樣一來,就會導致匹配的數組的索引的變化,作為開發人員的你,必須得一行一行代碼地修改。因此聰明的開發人員又想到一個好方法,把這些分組進行命名,只需要對名稱進行訪問分組,不通過索引來訪問了,就可以避免這個問題。那么怎么樣來命名呢?可以采用(?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() 結果輸出如下:
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'}如有疑問請留言或者到本站社區交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
新聞熱點
疑難解答