Quantifiers in the "re" module are used to specify how many times a pattern should be matched in a regular expression. Quantifiers are denoted by special characters that specify the number of times a pattern should be matched, such as:
*: Matches the preceding pattern zero or more times.+: Matches the preceding pattern one or more times.?: Matches the preceding pattern zero or one time.{m}: Matches the preceding pattern exactly "m" times.{m,n}: Matches the preceding pattern between "m" and "n" times.Here are some examples of using quantifiers in the "re" module in Python:
import retext = "The quick brown fox jumps over the lazy dog."pattern1 = "o*" # Match zero or more "o" characterspattern2 = "o+" # Match one or more "o" characterspattern3 = "o?" # Match zero or one "o" characterpattern4 = "o{2}" # Match exactly two "o" characterspattern5 = "o{1,3}" # Match between one and three "o" characters# Use the findall() function to find all matches of the pattern in the textmatches1 = re.findall(pattern1, text)matches2 = re.findall(pattern2, text)matches3 = re.findall(pattern3, text)matches4 = re.findall(pattern4, text)matches5 = re.findall(pattern5, text)print("Matches for pattern1:", matches1)print("Matches for pattern2:", matches2)print("Matches for pattern3:", matches3)print("Matches for pattern4:", matches4)print("Matches for pattern5:", matches5) |
In this example, we are using different quantifiers in regular expressions to match different patterns in the given text. We are using the findall() function to find all occurrences of the pattern in the text, and then printing out the matches for each pattern.
Note that quantifiers can be combined with other regular expression syntax, such as character classes and grouping with parentheses, to create more complex patterns.