Similar to Java. Use re.error exception:
import re
try:
re.compile('[')
is_valid = True
except re.error:
is_valid = False
Answer from falsetru on Stack Overflowexception
re.errorException 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.
Similar to Java. Use re.error exception:
import re
try:
re.compile('[')
is_valid = True
except re.error:
is_valid = False
exception
re.errorException 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.
Another fancy way to write the same answer:
import re
try:
print(bool(re.compile(input())))
except re.error:
print('False')
How to check is a string is a valid regex - python? - Stack Overflow
Python: check regex expression - Stack Overflow
python - Verify if string is valid regex? - Stack Overflow
python - Validate user input using regular expressions - Stack Overflow
Videos
Using a while True loop only break out with break if you got a right answer:
while True:
user_name = input("Please enter your name: ")
if not re.match("^[A-Za-z]*$", user_name):
print ("Error! Make sure you only use letters in your name")
else:
print("Hello "+ user_name)
break
user_name = '1' #something that doesn't validate
while not re.match("^[A-Za-z]*$", user_name):
user_name = input("Please enter your name: ")
print ("Error! Make sure you only use letters in your name")
else:
print("Hello! "+ user_name)
import re
pattern = re.compile("^([A-Z][0-9]+)+$")
pattern.match(string)
One-liner: re.match(r"pattern", string) # No need to compile
import re
>>> if re.match(r"hello[0-9]+", 'hello1'):
... print('Yes')
...
Yes
You can evaluate it as bool if needed
>>> bool(re.match(r"hello[0-9]+", 'hello1'))
True
I want to check if a string contains only letters a, b, c, and +.
I am checking in this way:
re.compile(r'[abc\+]')
But when I check against
acbbbaa+aa and aabbi+aaa I got both matched.
What am I doing wrong?