Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression for AlphaNumeric, Hyphen and Underscore without any space [duplicate]

Tags:

java

regex

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_-]*]

like image 338
Gautam R Avatar asked Jul 08 '16 11:07

Gautam R


People also ask

How do you represent alphanumeric in regular expression?

The regex \w is equivalent to [A-Za-z0-9_] , matches alphanumeric characters and underscore.

How do you add a hyphen in regex?

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 hyphen alphanumeric character?

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 replace non alphanumeric characters with empty strings?

The approach is to use the String. replaceAll method to replace all the non-alphanumeric characters with an empty string.


2 Answers

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

like image 94
abubaker Avatar answered Nov 11 '22 17:11

abubaker


You can use ^[\w-]*$ where \w means:

  • any letter in the range a-z, A-Z,
  • any digit from 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

like image 22
Thomas Ayoub Avatar answered Nov 11 '22 17:11

Thomas Ayoub