swati
swati

Reputation: 1283

Regular expression for alpahbet,underscore,hyphen,apostrophe only

I want a regular expression that accept only alphabets,hyphen,apostrophe,underscore. I tried

/^[ A-Za-z-_']*$/

but its not working. Please help.

Upvotes: 2

Views: 8601

Answers (5)

gagneet
gagneet

Reputation: 37259

You can use the following (in Java):

String acceptHyphenApostropheUnderscoreRegEx = "^(\\p{Alpha}*+((['_-]+)\\p{Alpha})?)*+$";

If you want to have spaces and @ also (as some have given above) try:

String acceptHyphenApostropheUnderscoreRegEx = "^(\\p{Alpha}*+((\\s|['@_-]+)\\p{Alpha})?)*+$";

Upvotes: 0

anubhava
anubhava

Reputation: 785276

Your regex is wrong. Try this:

/^[0-9A-Za-z_@'-]+$/

OR

/^[\w@'-]+$/

Hyphen needs to be at first or last position inside a character class to avoid escaping. Also if empty string isn't allowed then use + (1 or more) instead of * (0 or more)

Explanation:

^ assert position at start of the string
[\w@'-]+ match a single character present in the list below
Quantifier: Between one and unlimited times, as many times as possible
\w match any word character [a-zA-Z0-9_]
@'- a single character in the list @'- literally
$ assert position at end of the string

Upvotes: 5

Amit Joki
Amit Joki

Reputation: 59252

My best bet would be :

   /[A-Za-z-\'_@0-9]+/g

Upvotes: 0

Vasili Syrakis
Vasili Syrakis

Reputation: 9601

When using a hyphen in a character class, be sure to place it at the end of the character class as a best practice.

The reason for this is because the hyphen is used to signify a range of characters in the character class, and when it is at the end of the class, it will not create any ranges.

Upvotes: 0

Toto
Toto

Reputation: 91428

Move the hyphen at the end or the beginig of the character class or escape it:

^[ A-Za-z_'-]*$

or

^[- A-Za-z_']*$

or

^[ A-Za-z\-_']*$

If you want all letters:

^[ \pL_'-]*$

or

Upvotes: 4

Related Questions