Detailed Description: group naming using regular expressions in python, and python Regular Expressions
Detailed description of the group naming method using regular expressions in python
In the group match mode, you can access all matched tuples through the groups () function, or by group function. However, you can only access them through a digital index, if the product manager needs to modify the requirements one day and asks you to add a group to them, then the index of the matching array will change. As a developer, you must modify the code line by line. Therefore, smart developers think of another good way to name these groups. They only need to group the names and access them without using indexes. This problem can be avoided. How can we name it? You can use (? P <name> pattern) format.
Example:
# Python 3.6 # Cai junsheng # 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 ()
The output is as follows:
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'}
If you have any questions, please leave a message or go to the community on this site for discussion. Thank you for reading this article. Thank you for your support!