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
![](http://www.fcukthecode.com/wp-content/uploads/2022/02/Screenshot-from-2022-02-06-09-50-08.png)
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
![](http://www.fcukthecode.com/wp-content/uploads/2022/02/Screenshot-from-2022-02-06-09-58-31.png)