jliu83 jliu83 - 5 months ago 7
Python Question

Regex, test to see if characters other than exists

I'd like to use regex to see if any character other than a certain set exists.

For example, I'd like to test for the letters 'p', 'v', 'c' in a string. If any other characters are in the string, I want the test to return True. If only 'p', 'v', 'c' or a combination thereof exists, I want the test to return False.

'v' returns False

'pv' returns False

'pvc' returns False

'pd' returns True

'p(' returns True

'apvc' returns True

'xyz' returns True

How would I express this using re?
Thanks.

Answer

Use set(..)

if set(yourString) - set("pvc"):
    return True
else:
    return False

Edit: this can be turned into a single expression.

return set(your_string) - set('pvc')