Check if String Matches Regex in Python

Check if String Matches Regex in Python

  1. Import Regex Library in Python
  2. Compile the Regular Expression Pattern in Python
  3. 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.

Preet Sanghavi avatar Preet Sanghavi avatar

Preet writes his thoughts about programming in a simplified manner to help others learn better. With thorough research, his articles offer descriptive and easy to understand solutions.

LinkedIn GitHub

Related Article - Python String

  • Remove Commas From String in Python
  • Check a String Is Empty in a Pythonic Way
  • Convert a String to Variable Name in Python
  • Remove Whitespace From a String in Python
  • Extract Numbers From a String in Python
  • Convert String to Datetime in Python
  • Related Article - Python Regex

  • Python Regex Escape
  • Capture Groups With Regular Expression in Python
  • Python - Regular Expression to Match a Multiline Block of Text
  • Case Insensitive Regex in Python
  • Python Regex Group