python re module findall of function instance analysis

  • 2020-07-21 09:02:53
  • OfStack

This paper studies the re module findall() function. First, take a look at the example code:


>>> import re 
>>> s = "adfad asdfasdf asdfas asdfawef asd adsfas " 
 
>>> reObj1 = re.compile('((\w+)\s+\w+)') 
>>> reObj1.findall(s) 
[('adfad asdfasdf', 'adfad'), ('asdfas asdfawef', 'asdfas'), ('asd adsfas', 'asd')] 
 
>>> reObj2 = re.compile('(\w+)\s+\w+') 
>>> reObj2.findall(s) 
['adfad', 'asdfas', 'asd'] 
 
>>> reObj3 = re.compile('\w+\s+\w+') 
>>> reObj3.findall(s) 
['adfad asdfasdf', 'asdfas asdfawef', 'asd adsfas'] 

Follow the above code example to explain:

The findall function always returns a list of all the regular expression matches in a string, and here we focus on the representation of the "result" in the list, that is, the information contained in each element of the list is returned in findall.

When given a regular expression with multiple parentheses, the elements of the list are tuple consisting of multiple strings. The number of strings in tuple is the same as the logarithm of parentheses. The content of the string corresponds to the regular expression within each parentheses, and the order of arrangement is the order in which the parentheses appear.

When given a regular expression with 1 parenthesis, the elements of the list are strings, and the contents of the string correspond to the regular expression in parentheses (not the match of the entire regular expression).

When given a regular expression without parentheses, the element of the list is a string that matches the entire regular expression.

conclusion

That is the end of this article on python re module findall() function instance analysis, I hope to help you. Interested friends can continue to refer to other related topics in this site, if there is any deficiency, welcome to comment out. Thank you for your support!


Related articles: