How do I check if input string is a valid regular expression or not in Python

0 votes

HI all. Pretty simple question! 

Basically, in Java, I was able to use the following piece of code to check if my input string was a valid or an invalid regular expression. 

Check out the code:

boolean isRegex;
try {
  Pattern.compile(input);
  isRegex = true;
} catch (PatternSyntaxException e) {
  isRegex = false;
}

Now my question is that I want to know what the Python equivalent is of Pattern.compile() and PatternSyntaxException?

I am sure it exists in Python and that I am unaware of it. Using this in a project of mine.

All help appreciated!

Feb 12, 2019 in Python by Anirudh
• 2,090 points
13,016 views

1 answer to this question.

0 votes

Hi. Good question! Well, just like what we have in Java, for Python we have re.error exception just for this very purpose. Check out the code below to understand it better:

import re

try:
    re.compile('[')
    is_valid = True
except re.error:
    is_valid = False

What is re.error exception, you ask?

Here is the formal definition I got from the official documentation:

"Exception raised when a string passed to one of the functions here is not a valid regular expression or when some other error occurs during compilation or matching. "

Hope this helped! 

If you need to learn more about Python, It's recommended to join Python Training today.

Thanks!

answered Feb 12, 2019 by Nymeria
• 3,560 points

Related Questions In Python

0 votes
1 answer

how do i print only the last two letters in a string using regular expression in python?

S1="string1" S1[-2::] Output: g1 READ MORE

answered Jan 5, 2023 in Python by anonymous

edited Mar 5, 2025 2,417 views
0 votes
1 answer

How do I check if a list is empty in python?

Hey @Vedant, that's pretty simple and straightforward: if ...READ MORE

answered May 28, 2019 in Python by Karthik
2,301 views
0 votes
1 answer

How to write a regular expression to check whether an input is an identifier or not?

As per the documentation, an identifer can ...READ MORE

answered Aug 8, 2019 in Python by Neel
• 3,020 points
4,929 views
0 votes
1 answer

How do I check if a given Python string is a substring of another one?

Try using in like this: >>> x = 'hello' >>> y ...READ MORE

answered Nov 26, 2020 in Python by