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