Menu Close

Precompiled patterns – Regular Expression(Regex) in Python….FTC

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