re. findall Function Instance Usage in python

  • 2021-11-29 07:31:06
  • OfStack

1. The findall function returns a regular expression list of all matching results in a string.

2. If the regular without grouping is a regular match returned, the grouping returns a grouping match instead of the whole regular match.

Instances

Find all substrings that match pattern (no overlap) and put them in the list.


import re
lst = re.findall("[1-9]\d*","qw21313h1o58p4kjh8123jkh8435u")
for x in lst:
    print(x,end=" ")

# Output: 21313 1 58 4 812 3 843 5

Instance extension:

Function description in python3:


findall(pattern, string, flags=0)
    Return a list of all non-overlapping matches in the string.

    If one or more capturing groups are present in the pattern, return
    a list of groups; this will be a list of tuples if the pattern
    has more than one group.

    Empty matches are included in the result.

Two forms of use:


import re
kk = re.compile(r'\d+')
kk.findall('one1two2three3four4')
#[1,2,3,4]
 
# Note here findall() You can pass two parameters ;
kk = re.compile(r'\d+')
re.findall(kk,"one123")
#[1,2,3]

Among them, pay attention when including ():


import re

string="abcdefg  acbdgef  abcdgfe  cadbgfe"

# The difference between brackets and no brackets 
# Without parentheses 
regex=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']

Related articles: