Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a string is a valid regex in Python?

In Java, I could use the following function to check if a string is a valid regex (source):

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

Is there a Python equivalent of the Pattern.compile() and PatternSyntaxException? If so, what is it?

like image 829
alvas Avatar asked Oct 28 '13 09:10

alvas


People also ask

How do you check if a string is a regex python?

For checking if a string consists only of alphanumerics using module regular expression or regex, we can call the re. match(regex, string) using the regex: "^[a-zA-Z0-9]+$". re. match returns an object, to check if it exists or not, we need to convert it to a boolean using bool().

How do you check if a regex is valid or not?

new String(). matches(regEx) can be directly be used with try-catch to identify if regEx is valid. While this does accomplish the end result, Pattern. compile(regEx) is simpler (and is exactly what will end up happening anyway) and doesn't have any additional complexity.

How do you check if the input string is a valid regular expression?

compile() function to check if our regular expression is valid or not. Then we call input() function which basically prompts user for input string. Then we use re. fullmatch() function to test if user input is a valid alphanumeric string by checking it against our regex.

What is a valid regex?

The Validation (Regex) property helps you define a set of validation options for a given field. In general, this field property is used to perform validation checks (format, length, etc.) on the value that the user enters in a field. If the user enters a value that does not pass these checks, it will throw an error.


1 Answers

Similar to Java. Use re.error exception:

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

exception re.error

Exception raised when a string passed to one of the functions here is not a valid regular expression (for example, it might contain unmatched parentheses) or when some other error occurs during compilation or matching. It is never an error if a string contains no match for a pattern.

like image 143
falsetru Avatar answered Sep 20 '22 12:09

falsetru