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

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

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

我如何调整它允许空格?


当前回答

这个方法对我很管用

([\w ]+)

其他回答

只适用于字母:

^([a-zA-Z])+(\s)+[a-zA-Z]+$

对于字母数字值和_:

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

这个方法对我很管用

([\w ]+)

这是我的正则表达式 : @"^(?=.{ 3、15 }$)(?:(?:\ p {L} | \ p {N })[._()\[\]-]?)*$"

我只是在*之前的正则表达式的末尾添加了([\w]+)

@ ^(?”=(3.15%。 }$)(?:(?:\ p (L) | \ p (N })[._()\[\]-]?)([\ w] +) *美元”

现在字符串中允许有空格。

这在一开始就不允许有空间。但允许单词之间有空格。还允许在单词之间使用特殊字符。一个用于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