Example : literal matches

 Suppose you want to find and count all occurrences of the word "apple" in a given text. You can achieve this using a literal match with the regular expression "apple."

python
import re # Input text text = "I have an apple, and my friend has an apple too. We both love apples!" # Define the literal regex pattern pattern = r"apple" # Use the findall() function to find all matches in the text matches = re.findall(pattern, text) # Count the number of matches match_count = len(matches) # Output the results print(f"Input text: {text}") print(f"Number of 'apple' occurrences: {match_count}")

Explanation:

In this example, we are looking for the exact word "apple" within the input text. Here's how the code works:

  1. We import the re module, which provides support for regular expressions in Python.

  2. We define the input text, which contains multiple instances of the word "apple."

  3. The pattern variable is set to the regular expression "apple." Since this is a literal match, it will search for the exact word "apple" in the text.

  4. We use the re.findall() function to find all occurrences of the pattern in the input text. This function returns a list of all matches.

  5. We count the number of matches by finding the length of the matches list, which gives us the count of how many times "apple" appears in the text.

  6. Finally, we output the input text and the number of "apple" occurrences found in the text.

When you run this Python code, it will search for the literal string "apple" in the input text and print the count of how many times it appears. In this case, the word "apple" appears twice in the text, so the output will be:

arduino
Input text: I have an apple, and my friend has an apple too. We both love apples! Number of 'apple' occurrences: 2

This demonstrates how to perform a literal match with a regular expression in Python to find specific words or patterns within a text.

No comments:

Post a Comment