Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if a string only contains alphanumeric characters and dashes?

Tags:

The string I'm testing can be matched with [\w-]+. Can I test if a string conforms to this in Python, instead of having a list of the disallowed characters and testing for that?

like image 409
q3d Avatar asked Jun 08 '12 07:06

q3d


People also ask

How do you check if a string only has letters and numbers?

To check whether a String contains only unicode letters or digits in Java, we use the isLetterOrDigit() method and charAt() method with decision-making statements. The isLetterOrDigit(char ch) method determines whether the specific character (Unicode ch) is either a letter or a digit.

How do you know if a string contains alphanumeric?

The idea is to use the regular expression ^[a-zA-Z0-9]*$ , which checks the string for alphanumeric characters. This can be done using the matches() method of the String class, which tells whether this string matches the given regular expression.

Are dashes considered alphanumeric?

Is a dash an alphanumeric character? The login name must start with an alphabetic character and can contain only alphanumeric characters and the underscore ( _ ) and dash ( – ) characters. Full name can contain only letters, digits, and space, underscore ( _ ), dash ( – ), apostrophe ( ' ), and period ( . ) characters.

How do you check that a string contains only AZ AZ and 0 9 characters?

[A-Za-z0-9] matches a character in the range of A-Z, a-z and 0-9, so letters and numbers. + means to match 1 or more of the preceeding token.


1 Answers

If you want to test a string against a regular expression, use the re library

import re valid = re.match('^[\w-]+$', str) is not None 
like image 127
math Avatar answered Sep 20 '22 01:09

math