在JavaScript正则表达式中匹配0-9,a-z和1个特殊字符

时间:2019-02-22 21:32:16

标签: javascript

在JavaScript中,我目前有正则表达式:\w+。我知道这意味着要匹配字符a-z,A-Z,0-9和下划线,但是我也想匹配特殊字符*。

AT_17*abe有效AT17%abe无效

3 个答案:

答案 0 :(得分:2)

const re = new RegExp(/[a-zA-Z0-9*]/g);
console.log("*".match(re)); // match
console.log("123".match(re)); // match
console.log("abc".match(re)); // match
console.log("!@#$%^&".match(re)); // null
console.log("123!".match(re));  // Will match 1, 2, and 3 but not !

/[a-zA-Z0-9\*]/g的意思是“匹配小写字母a-z,大写字母A-Z,所有数字和*的任何值。

编辑:如注释中所指出的,无需转义*。

答案 1 :(得分:0)

使用测试而非匹配功能将其添加到丹尼斯答案中,

const regEx = new RegExp("^[A-Za-z0-9_*]*$");
console.log(regEx.test("6789")); // true
console.log(regEx.test("xyz")); // true
console.log(regEx.test("abc123")); // true
console.log(regEx.test("abc123*")); // true
console.log(regEx.test("123@#")); // false
console.log(regEx.test("AT_17*")); // true
console.log(regEx.test("AT17@abe")); // false

*的意思是“其中的任何数量”。

^表示字符串的开头。

$表示字符串的结尾。

答案 2 :(得分:0)

这对我有用。

a-zA-Z0-9_

我需要一个下划线。

var folder = 'fsvdsv_$ve';

if (folder.match("^[a-zA-Z0-9_]+$")) {

    console.log('yes');

} else {

    console.log('no');

}