How to Check if String Matches Regex in Python
- Import Regex Library in Python
- Compile the Regular Expression Pattern in Python
- Match the Input String With Regex Pattern in Python
In this tutorial, we will be learning how to check if a string matches the regex in Python.
Import Regex Library in Python
import re
Let us take a sample string to work with.
string = "C1N200J1"
We will use this string to match our pattern. We will now use the re.compile()
function to compile a regular expression pattern.
Compile the Regular Expression Pattern in Python
pattern = re.compile("^([A-Z][0-9]+)+$")
We have saved the desired pattern in the pattern
variable, which we will use to match with any new input string.
Match the Input String With Regex Pattern in Python
We will now use the match()
function to search the regular expression method and return us the first occurrence.
print(pattern.match(string))
The above code will return the match object if the pattern is found and returns None
if the pattern does not match. For our input string, we get the below output.
<re.Match object; span=(0, 8), match='C1N200J1'>
The above output shows that our input string matches the regex pattern from span 0 to 8. Let us now take a new string that does not match our regex pattern.
new_string = "cC1N2J1"
We will now repeat the above matching process and see the output for our new string.
print(pattern.match(new_string))
We get the below output on running the above code.
None
The above output shows that our input string does not match the required regex pattern.
Thus, we can determine if our string matches the regex pattern with the above method.
Related Article - Python String
- How to Remove Commas From String in Python
- How to Check a String Is Empty in a Pythonic Way
- How to Convert a String to Variable Name in Python
- How to Remove Whitespace From a String in Python
- How to Extract Numbers From a String in Python
- How to Convert String to Datetime in Python