Match an entire string with spaces if it contains at least a letter

I need a RegEx that matches a string containing a letter, numbers, some special characters and spaces. However, RegEx should reject a string consisting of only spaces. I created a template, but it does not work.

import re

pattern = r"^[/<>'\.\,\-\?\[\] \w\d]+$"

print bool(re.match(pattern, "Hi, how are you?"))
print bool(re.match(pattern, "Hi, how are you? &*() "))
print bool(re.match(pattern, " "))

this is the result of the previous snippet:

True
False
True

I need the third test to fail, like the second. I know I can do this using more than just a regular expression, but I would like to know if only a regular expression can be used. Thanks

+4
source share
2 answers

You can use a negative result in your regex:

patter = r"^(?!\s*$)[<>'.,?\[\] \w\d-]+$"

(?!\s*$) - lookahead, , 0 .

:

>>> print bool(re.match(patter, " "))
False
+3

^(?=.*\S)[<>'.,?\[\] \w\d-]+$

\S non .

0

Source: https://habr.com/ru/post/1611652/


All Articles