Menu Close

Precompiled patterns using Regular Expressions

Python makes regular expressions available through the re module.

For the first part in using regular expressions and matching the string
you can visit this link –> Matching the beginning of a string (Regex) Regular Expressions in python

The re.search() method takes a regular expression pattern and a string and searches for that pattern within the string. If the search is successful, search() returns a match object or None otherwise.
For the second part in using regular expression and searching the string
visit –> Searching – Regular Expressions (Regex) in Python

precompiled_pattern

Compiling a pattern allows it to be reused later on in a program. However, note that Python caches recently-used expressions, so “programs that use only a few regular expressions at a time needn’t worry about compiling regular expressions”.

import re
precompiled_pattern = re.compile(r"(\d+)")
matches = precompiled_pattern.search("The answer is 41!")
print(matches.group(1))
# Output: 41

matches = precompiled_pattern.search("Or was it 42?")
print(matches.group(1))
# Output: 42

OUTPUT:
41
42


ILLUSTRATION USING PYTHON3 CLI

executed using python3 Linux terminal

import re
precompiled_pattern = re.compile(r"(.*\d+)")
matches = precompiled_pattern.match("The answer is 41!")
print(matches.group(1))
# Output: The answer is 41

matches = precompiled_pattern.match("Or was it 42?")
print(matches.group(1))
# Output: Or was it 42

OUTPUT:
The answer is 41
Or was it 42

ILLUSTRATION USING PYTHON3 CLI

executed using python3 linux terminal

Morae Q!

  1. Program to get dictionary items, use update module and items module.
  2. Regular expression allowing certain set of characters.
  3. Compute the Sum of Cosine Series.
  4. Find the Sum of Sine Series.
  5. Remove the Vowels from the string.
  6. Find All Non-Overlapping strings/characters using regular expressions .
  7. Check whether the given string is Panagram or not.
  8. Replacing strings using Regular Expression Regex.
  9. Check whether the given number is Strong number or not.
  10. Find the numbers divisible by a input numbers within the given range.
  11. Change the behaviour of the Regular Expression using flags.
  12. Find the exponentiation of a number.
  13. Find all prime numbers in a range using Sieve of Eratosthenes.
  14. Convert decimal equivalent into binary, hexadecimal and octal.
  15. Compute the area of a farmers field in feet.
  16. Compute time from number of days/hours to seconds.
  17. Precompiled patterns using Regular Expressions .
  18. Compute the price of the cake on the nth day.
  19. Compute the number of possible non-increasing arrays.
  20. Find the type of spinach using the calorie value.