在JavaScript中,我目前有正则表达式:\w+
。我知道这意味着要匹配字符a-z,A-Z,0-9和下划线,但是我也想匹配特殊字符*。
AT_17*abe
有效AT17%abe
无效
答案 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');
}