简体   繁体   中英

Regular expression in JS for alphanumeric, dot and hyphen

I need a JS regular expression which should allow only the word having alphanumeric, dot and hyphen.

Let me know this is correct.

var regex =  /^[a-zA-Z_0-9/.-]+$/;

Almost. That will also allow underscores and slashes. Remove those from your range:

var regex =  /^[a-zA-Z0-9.-]+$/;

This will also not match the empty string. That may be what you want, but it also may not be what you want. If it's not what you want, change + to * .

The first simplifications I'd make are to use the "word character" shorthand '\\w', which is about the same as 'a-zA-Z', but shorter, and automagically stays correct when you move to other languages that include some accented alphabetic characters, and the "digit character" shorthand '\\d'.

Also, although dot is special in most places in regular expressions, it's not special inside square brackets, and shouldn't be quoted there. (Besides, the single character quote character is back -slash, not forward-slash. That forward-slash of yours inside the brackets is the same character that begins and ends the RE, and so is likely to prematurely terminate the RE and so cause a parse error!) Since we're completely throwing it away, it no longer matters whether it should be forward-slash or back-slash, quoted or bare.

And as you've noticed, hyphen has a special meaning of "range" inside brackets (ex: az), so if you want a literal hyphen you have to do something a little different. By convention that something is to put the literal hyphen first inside the brackets.

So my result would be var regex = /^[-.\\w\\d]+$/;

(As you've probably noticed, there's almost always more than one way to express a regular expression so it works, and RE weenies spend as much time on a) economy of expression and b) run-time performance as they do on getting it "correct". In other words, you can ignore much of what I've just said, as it doesn't really matter to you. I think all that really matters is a) getting rid of that extraneous forward-slash and b) moving the literal hyphen to be the very first character inside the square brackets.)

(Another thought: very frequently when accepting alphabetic characters and hyphens, underscore is acceptable too ...so did you really mean to have that underscore after all?)

(Yet another thought: sometimes the very first character of an identifier must be an alpha, in which case what you probably want is var regex = /^\\w[-.\\w\\d]*$/; You may want a different rule for the very first character in any case, as the naive recipe above would allow "-" and "." as legitimate words of length one.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM