我想检查一个字符串是否只包含特定类型的字符,并且字符都是字母、数字、点、下划线和破折号。
如果字符串包含除我提到的字符之外的其他字符,那么它应该导致错误值。
以下是有关正则表达式如何工作的示例:
const regex = /regexpression/;
const string1 = "abra-ibra_cadabra.2";
// Should console log true
console.log(regex.test(string1));
const string2 = "!abra-ibra";
// Should console log false
console.log(regex.test(string2));
const string3 = "(abra)_ibra";
// Should console log false
console.log(regex.test(string3));
Run Code Online (Sandbox Code Playgroud)
您可以使用 JavaScript test() 方法,如下所示:
\n\nconst string1 = "abra-ibra_cadabra.2";\r\nconst string2 = "!abra-ibra";\r\nconst string3 = "(abra)_ibra";\r\n\r\nlet patt = /^(\\w|\\.|-)+$/;\r\n\r\nconsole.log(\'string1:\', patt.test(string1));\r\nconsole.log(\'string2:\', patt.test(string2));\r\nconsole.log(\'string3:\', patt.test(string3));Run Code Online (Sandbox Code Playgroud)\r\n解释:
\n\n^ : asserts position at start of the string,\n\n$ : asserts position at the end of the string,\n\n+ : Quantifier \xe2\x80\x94 Matches between one and unlimited times,\nRun Code Online (Sandbox Code Playgroud)\n\n捕获组:
\n\n在括号之间,每个选项都用“|”分隔 (或)符号:
\n\n(\\w|\\.|-)\nRun Code Online (Sandbox Code Playgroud)\n\n\n\n\n第一种选择:
\n
\\w : matches any word character (equal to [a-zA-Z0-9_])\nRun Code Online (Sandbox Code Playgroud)\n\n\n\n\n第二种选择:
\n
\\. : matches the character . literally (case sensitive)\nRun Code Online (Sandbox Code Playgroud)\n\n\n\n\n第三种选择:
\n
- : matches the character - literally (case sensitive) \nRun Code Online (Sandbox Code Playgroud)\n