Parentheses matching problem in Python regular expressions _python

Source: Internet
Author: User

Problem:

m = Re.findall (' [0-9]*4[0-9]* ', ' [4] ')
can match to 4.
m = Re.findall (' ([0-9]) *4 ([0-9]) * ', ' [4] ')
Match less than 4.
What is this for? PS, this is a simplified description, I want to use a more complex than this, so to use (), to represent a sequence of matches.
To add, when I put it in the notepad++, both of them could be matched, and I don't know why Python doesn't.

Answer:

Python's regular use () will match, so the return result is [', '], is a match in two (). To achieve the original matching effect, is to match the 4 out, there are two ways to solve:

1. The outermost bracket, which becomes: M = Re.findall (([0-9]) *4 ([0-9]) *, "[4]"), returns the first element of the result that matches the result.
2. Remove () The match result returns, joins before the parenthesis:, becomes m = Re.findall ('?: \ d) *4 (?: \ d) * ', ' [4] ', return the result is the result to match.

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.