我想要一个正则表达式,防止符号,只允许字母和数字。下面的正则表达式工作得很好,但它不允许单词之间有空格。

^[a-zA-Z0-9_]*$

例如,当使用这个正则表达式时,“HelloWorld”是可以的,但“HelloWorld”不匹配。

我如何调整它允许空格?


当前回答

这个正则表达式

^\w+(\s\w+)*$

将只允许单词之间有一个空格,不允许开头或结尾空格。

正则表达式解释如下:

^ Assert position at start of the string \w+ Match any word character [a-zA-Z0-9_] Quantifier: + Between one and unlimited times, as many times as possible, giving back as needed [greedy] 1st Capturing group (\s\w+)* Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy] \s Match any white space character [\r\n\t\f ] \w+ Match any word character [a-zA-Z0-9_] Quantifier: + Between one and unlimited times, as many times as possible, giving back as needed [greedy] $ Assert position at end of the string

其他回答

只需在正则表达式模式的末尾添加一个空格,如下所示:

[a-zA-Z0-9_ ]

如果你正在使用JavaScript,那么你可以使用这个正则表达式:

/^[a-z0-9_.-\s]+$/i

例如:

/^[a-z0-9_.-\s]+$/i.test("") //false
/^[a-z0-9_.-\s]+$/i.test("helloworld") //true
/^[a-z0-9_.-\s]+$/i.test("hello world") //true
/^[a-z0-9_.-\s]+$/i.test("none alpha: ɹqɯ") //false

这个正则表达式的唯一缺点是字符串完全由空格组成。" "也会显示为true。

试一试:

^(\w+ ?)*$

解释:

\w             - alias for [a-zA-Z_0-9]
"whitespace"?  - allow whitespace after word, set is as optional

这在一开始就不允许有空间。但允许单词之间有空格。还允许在单词之间使用特殊字符。一个用于FirstName和LastName字段的良好正则表达式。

\w+.*$

这个正则表达式

^\w+(\s\w+)*$

将只允许单词之间有一个空格,不允许开头或结尾空格。

正则表达式解释如下:

^ Assert position at start of the string \w+ Match any word character [a-zA-Z0-9_] Quantifier: + Between one and unlimited times, as many times as possible, giving back as needed [greedy] 1st Capturing group (\s\w+)* Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy] \s Match any white space character [\r\n\t\f ] \w+ Match any word character [a-zA-Z0-9_] Quantifier: + Between one and unlimited times, as many times as possible, giving back as needed [greedy] $ Assert position at end of the string