[英]Javascript regular expression that allow only alphabet, space and - only
I want a regular expression that allow only alphabet, one space after word, and - only it will not accept two word but single space after word allowed.我想要一个只允许字母表,单词后一个空格的正则表达式,并且 - 只有它不接受两个单词,但允许单词后一个空格。 Any ther special character are not allowed.不允许任何特殊字符。 Example例子
John -> true
John(space) -> true
John-Doe -> true
John-Doe(space) -> true
(space)John -> false
John Doe -> false
I am trying using this [a-zA-Z-][a-zA-Z -] But not working exactly.我正在尝试使用此 [a-zA-Z-][a-zA-Z -] 但无法正常工作。 Please help.请帮忙。
If you don't want to allow consecutive hyphens --
in the pattern, you might write the pattern as:如果您不想在模式中使用连续的连字符--
,您可以将模式写为:
^[A-Z][a-z]+ ?(?:-[A-Z][a-z]+ ?)?$
Explanation解释
^
Start of string ^
字符串开始[AZ][az]+?
Match a char AZ and 1+ chars az followed by an optional space (or [A-Za-z]+
if you want to allow mixed chars)匹配一个字符 AZ 和 1+ 个字符 az 后跟一个可选空格(或者[A-Za-z]+
如果你想允许混合字符)(?:-[AZ][az]+?)?
Optionally match the same as the preceding pattern with a leading -
可选地匹配与前面的模式相同的前导-
$
End of string $
字符串结束See a regex demo查看正则表达式演示
If you want to allow all mixed chars with an optional space at the end:如果你想允许所有混合字符在末尾有一个可选的空格:
^[A-Za-z-]+ ?$
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.