Home > Software design >  Regex that checks if string only contains numbers and special characters
Regex that checks if string only contains numbers and special characters

Time:12-29

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.

CodePudding user response:

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

  • Related