0

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?

1 Answer 1

2

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: ]+'
Sign up to request clarification or add additional context in comments.

4 Comments

For the first expression to work, you need to add anchors like so: r'^[a-zA-Z0-9: ]+$'. The second expression should work fine as-is.
I am using negative matching. Its not not working, for both[valid and invalid] strings it re.match is returning None
It must be a Python thing. According to the documentation, match matches "zero or more characters at the beginning of string". Try search instead of match, so print re.search(regex, myString). See documentation: docs.python.org/2/library/re.html
+1 and accepted. Worked with search, but I was doing a mistake. I was reading file line by line and I forgot to consider newline character. Now it is working. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.