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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 15:29:59  来源:igfitidea点击:

JavaScript regular expression ( alphanumeric characters with _-)

javascriptregexalphanumeric

提问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 (yourPhraseis 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 表中与 _ 或以上匹配的任何字符。