pam
pam

Reputation: 143

JQuery Regular expression to accept alphanumeric characters and ' , -

I'm trying to figure out how to get my regular expression to accept certain special characters: ', , and - along with alphanumeric characters. I've had a stab at it but to no avail, and I'm quite new to regex, can anyone help?

Here was my attempt which, surprisingly, didn't work...

/^\d+/,\'\-\$/i

Upvotes: 2

Views: 8147

Answers (3)

Sean Vieira
Sean Vieira

Reputation: 159895

\d is shorthand for [0-9], which is not any alphanumeric character.

/^[\w,'-]+$/i

should do the trick.

What this is saying:

^ - match the start of the line
[ - match any of the following characters (group #1)
    \w - any word (meaning differs depending on locale;
         generally, any letter, number or the `-` character.)
    ,  - a comma
    '  - an apostrophe
    -  - a dash
] - end group #1
+ - one or more times
$ - match the end of the line
/i - set case-insensitivity.

Upvotes: 2

Tim Pietzcker
Tim Pietzcker

Reputation: 336128

Try

/^[\w',-]*$/

(assuming you mean ASCII letters, digits and underscore by "alphanumeric").

Upvotes: 4

simon
simon

Reputation: 16280

Something like this?

/[0-9a-zA-Z',-]+/

if it has to be a full string, you can use

/^[0-9a-zA-Z',-]+$/

Upvotes: 7

Related Questions