I would like to have a regular expression that checks if the string contains Alphanumerics, Hyphen and Underscore. There should not be any spaces or other special characters other these three. My string will be under either of these 2 patterns.
XYZ0123_123456
ABCdefGHI-727
I have already tried this expression. But it didnt workout. [[a-zA-Z0-9_-]*]
The regex \w is equivalent to [A-Za-z0-9_] , matches alphanumeric characters and underscore.
In regular expressions, the hyphen ("-") notation has special meaning; it indicates a range that would match any number from 0 to 9. As a result, you must escape the "-" character with a forward slash ("\") when matching the literal hyphens in a social security number.
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.
The approach is to use the String. replaceAll method to replace all the non-alphanumeric characters with an empty string.
Working
Here is the quick solution.
String regex = "^[a-zA-Z0-9_-]*$";
sampleString.matches(regex);
(^) anchor means start of the string
($) anchor means end of the string
A-Z , a-z represent range of characters
0-9 represent range of digit
( _ ) represent underscore
( - ) represent hyphen
You can use ^[\w-]*$
where \w
means:
a-z
, A-Z
,0 to 9
,underscore
The error you made was to encapsulate you correct regex ([a-zA-Z0-9_-]*
== [\w-]*
) within a character class, loosing the quantifier (*
) meaning
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With