avi
avi

Reputation: 9636

Regex negative matching with python

I have a string which is allowed to contain only alphabets, numbers, empty spaces and symbol ':'. So I wrote the following code :

regex = r'![a-zA-Z0-9\:\ ]+'
print re.match(regex, myString)

However it does not seem to work. I tried different combinations r'?!([a-zA-Z0-9\:\ ])+' and also with re.search, but it does not seem to work. Any help?

Upvotes: 0

Views: 434

Answers (1)

Gergo Erdosi
Gergo Erdosi

Reputation: 42093

If you want a positive match (valid characters), then use:

r'^[a-zA-Z0-9: ]+$'

If you want a negative match (whether the string has invalid characters), then:

r'[^a-zA-Z0-9: ]+'

Upvotes: 2

Related Questions