Detailed explanation of nested instances using regular expressions in python, python Regular Expressions

Source: Internet
Author: User

Detailed explanation of nested instances using regular expressions in python, python Regular Expressions

Detailed description of nested instances using regular expressions in python

Because the group itself is a complete regular expression, you can nest the group in other groups to build more complex expressions. The following is an example of group nesting:

# Python 3.6 # Cai junsheng # http://blog.csdn.net/caimouse/article/details/51749579 # import re def test_patterns (text, patterns): "" Given source text and a list of patterns, look for matches for each pattern within the text and print them to stdout. "# Look for each pattern in the text and print the results for pattern, desc in patterns: print ('{! R} ({}) \ n'. format (pattern, desc) print ('{! R }'. format (text) for match in re. finditer (pattern, text): s = match. start () e = match. end () prefix = ''* (s) print ('{}{! R }{}'. format (prefix, text [s: e], ''* (len (text)-e), end ='',) print (match. groups () if match. groupdict (): print ('{}{}'. format (''* (len (text)-s), match. groupdict (),) print () return

Example:

# Python 3.6 # Cai junsheng # http://blog.csdn.net/caimouse/article/details/51749579 # from re_test_patterns_groups import test_patterns ('ababbba ', [(r 'a (a *) (B *))', 'A followed by 0-n a and 0-n B ')],)

 

The output is as follows:

'a((a*)(b*))' (a followed by 0-n a and 0-n b) 'abbaabbba' 'abb'    ('bb', '', 'bb')   'aabbb'  ('abbb', 'a', 'bbb')     'a' ('', '', '')

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!

Related Article

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.