Python Regular Expression exercises

Source: Internet
Author: User

1. Import re

Cr = Re. Compile ("how to write ")
S = "abcd123d123ad1v123"
Print Cr. findall (s)

I want to find a string that starts with a and ends with a string of 123, but does not contain a string of 123.

For example, the result of the above question should be abcd123 and ad1v123.


2.

Import re
Cr = Re. Compile ("how to write ")
S = "a123abvpd123d" p "f12ab123sabd123f1123abc"
Print Cr. findall (s)

I want to find the substring that starts with string 123 and ends with string AB, but does not contain the substring 123 and "p.
For example, the result of the above question should be 123ab, 123sab, and 123ab.


Answer:

1. The key here is .*? Combined Use

import reprint re.findall(r'a.*?123','abcd123d123ad1v123')

2.

import reprint re.findall(r'123[^p|123]*?ab',"a123abvpd123d'p'f12ab123sabd123f1123abc")
The above two conditions are met, but the two minimum matching conditions are obtained.

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.