Matching of parentheses in python regular expressions

Source: Internet
Author: User
This article mainly introduces the question of matching parentheses in python regular expressions. For more information, see:

M = re. findall ('[0-9] * 4 [0-9] *', '[4]')
It can be matched to 4.
M = re. findall ('([0-9]) * 4 ([0-9]) *', '[4]')
No matching 4.
Why? PS. this is a simplified description. the regular expression I want to use is more complex than this one, so I need to use () to indicate a sequence matching.
In addition, when I put it in notepad ++, both methods can be matched. I don't know why python doesn't work.

Answer:

In the python regular expression, () is used for matching. Therefore, the returned result is ['',''], that is, matching in two. To achieve the original matching effect, there are two solutions to Match 4:

1. the outermost layer is enclosed by braces and becomes m = re. findall ('([0-9]) * 4 ([0-9]) *)', '[4]'), the first element of the returned result is the matching result.
2. remove () and add question mark (?) before brackets? :, To m = re. findall ('(? : \ D) * 4 (? : \ D) * ',' [4] '). The Returned result is the result to be matched.

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.