Regex that checks if string only contains numbers and special characters

Question:

I am trying to make an if function that checks if a string contains only a mixture of numbers and any special characters. For example:

Input: "Hello"
>>> False

Input: "$34&@!5^"
>>> True

Input: "Hello34#&%"
>>> False

I’m new to Regex and I’m not sure how to write the Regex for this. I know checking for special characters is r'^[_W]+$' , and isdigit() can be used to check numbers only, but how do I combine both? I’m confused on how to combine [0-9] and the other symbols to write a Regex for this.

Asked By: cloud

||

Answers:

You can use ^[W0-9_]+$ to match all non-word characters, _, and 0-9.

Answered By: ruohola
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.