简体   繁体   English

javascript中的正则表达式仅匹配字母或空格

[英]Regular expression in javascript to match only letters or spaces

I have the following expression to validate a "name": 我有以下表达式来验证“名称”:

/^([a-z\s?]{4,120})[^\s]$/i

But I do not know why accepts special characters: Alex@ is a valid match. 但我不知道为什么接受特殊字符: Alex@是一个有效的匹配。

It should be invalid because I have not specified that contains special characters. 它应该是无效的,因为我没有指定包含特殊字符。

What you want is a minimum of 4 characters - you're trying to get it to work with is expecting at least 5 characters because of the non-optional [^\\s] character at the end. 你想要的是至少4个字符 - 由于最后的非可选[^\\s]字符,你试图使用它至少需要5个字符。 Moreover, [^\\s] will actually match any character that isn't a space - I'd bet you want to restrict that to being just letters as well? 而且, [^\\s]实际上会匹配任何不是空格的角色 - 我敢打赌你想把它限制为只是字母?

Try this instead: 试试这个:

^[a-z\s?]{3,119}[a-z]$

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM