Detailed Description: group naming using regular expressions in python, and python Regular Expressions

Source: Internet
Author: User

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!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.