JavaScript 正则表达式(带有 _- 的字母数字字符)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12175553/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript regular expression ( alphanumeric characters with _-)
提问by krizajb
I am having trouble forming regular expression containing all alphanumeric characters and one or two specific characters, such us _
or -
.
我在形成包含所有字母数字字符和一两个特定字符(例如 us_
或-
.
This expression works for all alphanumeric characters /^[0-9a-zA-Z]+$/
.
此表达式适用于所有字母数字字符/^[0-9a-zA-Z]+$/
。
回答by Gabber
Add the special characters inside the square brackets
在方括号内添加特殊字符
/^[0-9a-zA-Z_-]+$/
To use this regex in javascript use this code (yourPhrase
is the string you check vs the regexp)
要在 javascript 中使用此正则表达式,请使用此代码(yourPhrase
是您检查的字符串与正则表达式)
var rexp = /^[0-9a-zA-Z_-]+$/
if(rexp.test(yourPhrase)){
//code to handle the test
}
回答by tomsv
Try this:
试试这个:
/^[0-9a-zA-Z-_]+$/
If you enter the dash sign "-" at a position where it can be interpreted as a range such as _- it would mean any characters matching _ or above in the ascii table.
如果在可以解释为范围(例如 _-)的位置输入破折号“-”,则表示在 ascii 表中与 _ 或以上匹配的任何字符。