Python re module FindAll () detailed

Source: Internet
Author: User

Writing code today, when writing to Zhengze, encountered a pit, which is the FindAll () function under the RE module.

Below I will combine the code to record

Importrestring="ABCDEFG acbdgef ABCDGFE cadbgfe"#the difference between parentheses and without parentheses#with no parenthesesRegex=re.compile ("((\w+) \s+\w+)")Print(Regex.findall (string))#output: [(' ABCDEFG acbdgef ', ' ABCDEFG '), (' Abcdgfe cadbgfe ', ' ABCDGFE ')]regex1=re.compile ("(\w+) \s+\w+")Print(Regex1.findall (string))#output: [' ABCDEFG ', ' ABCDGFE ']Regex2=re.compile ("\w+\s+\w+")Print(Regex2.findall (string))#output: [' ABCDEFG acbdgef ', ' Abcdgfe cadbgfe ']

With 2 parentheses in the first regex, we can see that its output is a list containing 2 tuple

The second regex has 1 parentheses, and the output is what the parentheses match, not the result that the entire expression matches.

The third regex does not have parentheses, and its output is what the entire expression matches.

Conclusion: FindAll () Returns the result that the parentheses match (for example, regex1), and multiple parentheses return the result (such as a regex) where the parentheses match, or return the entire statement (such as REGEX2) if no parentheses are returned. So when extracting the data, you need to pay attention to this pit.

Python re module FindAll () detailed

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.