JavaScript 正则表达式 - 如何检查字符串是否仅包含字母、数字、破折号、下划线和点

you*_*lil -2 javascript regex

我想检查一个字符串是否只包含特定类型的字符,并且字符都是字母、数字、点、下划线和破折号。

如果字符串包含除我提到的字符之外的其他字符,那么它应该导致错误值。

以下是有关正则表达式如何工作的示例:

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)

Sam*_*tas 6

您可以使用 JavaScript test() 方法,如下所示:

\n\n

\r\n
\r\n
const 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
\r\n
\r\n

\n\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,\n
Run Code Online (Sandbox Code Playgroud)\n\n

捕获组:

\n\n

在括号之间,每个选项都用“|”分隔 (或)符号:

\n\n
(\\w|\\.|-)\n
Run Code Online (Sandbox Code Playgroud)\n\n
\n

第一种选择:

\n
\n\n
\\w     : matches any word character (equal to [a-zA-Z0-9_])\n
Run Code Online (Sandbox Code Playgroud)\n\n
\n

第二种选择:

\n
\n\n
\\.     : matches the character . literally (case sensitive)\n
Run Code Online (Sandbox Code Playgroud)\n\n
\n

第三种选择:

\n
\n\n
-     : matches the character - literally (case sensitive) \n
Run Code Online (Sandbox Code Playgroud)\n