Python regular expression returns the first match to the character and the robustness of the query

Source: Internet
Author: User

Re.findall (pattern,string) searches for all matching characters, returns a list, gets the first match to be accessed Re.findall (pattern,string) [0], but returns an empty list if the FindAll does not match successfully. When you use the list subscript to access the element, you will be quoted Indexerror:list index out of range.

Such as:

>>>re.findall ('abc','abd') []>> >re.findall ('abc','abd' ) <input> "  in <module>indexerror:list index out of range

We can add a "|$" behind the pattern to generate a default ' element:

>>>re.findall ('abc|$','abd') [0] >>>re.findall ('abc|$','abcdef ' # Note that the previous ' element ' will be appended, regardless of whether it matches or not ['abc']

The same applies to Re.search

>>> re.search ('\d+|$'aa33bbb44'). Group ()  're.search'>>> ('\d+|$' ) aazzzbbb ' ). Group ()'

If you don't add |$:

>>>re.search ('\d+'aazzzbbb'" ) <input> "  in <module>'nonetype'group '

Reference: Https://stackoverflow.com/questions/38579725/return-string-with-first-match-regex

Python regular expression returns the first match to the character and the robustness of the query

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.