[英]Regular expression for a name that can contain not more than one space character
I'm struggling to find a regular expression that matches a name that can contain a space in it.我正在努力寻找与其中可以包含空格的名称匹配的正则表达式。 So far this is what I've tried:
到目前为止,这是我尝试过的:
^(?![\s]+$)(?![\s]{2,})[a-zA-Z\s]{2,25}$
Unfortunately I'm not so good on regex.不幸的是,我对正则表达式不太擅长。 The name can contain only letters and optionally a space character, and if a space is present there must be no more than one space character in the word.
名称只能包含字母和可选的空格字符,如果存在空格,则单词中的空格字符不得超过一个。 The whole name length (counting also the space) must be between 2 and 25 characters long.
整个名称长度(包括空格)必须在 2 到 25 个字符之间。 Here some examples of names that have to match:
下面是一些必须匹配的名称示例:
Here some examples of names that have not to match the regular expression:下面是一些不必匹配正则表达式的名称示例:
The last requirement is that I have to use this regular expression both in javascript and php.最后一个要求是我必须在 javascript 和 php 中都使用这个正则表达式。
Thanks in advance!提前致谢!
The pattern ^(??[\s]+$)(,,[\s]{2,})[a-zA-Z\s]{2,25}$
that you tried matches:您尝试的模式
^(??[\s]+$)(,,[\s]{2,})[a-zA-Z\s]{2,25}$
匹配:
^(?![\s]+$)
^(?![\s]+$)
(?,[\s]{2,})
(?,[\s]{2,})
[a-zA-Z\s]{2,25}$
[a-zA-Z\s]{2,25}$
There is no restriction to match a single space没有限制匹配单个空格
in the whole string在整个字符串中
Note that \s
could also match a newline or a tab.请注意,
\s
也可以匹配换行符或制表符。
What you could do is assert 2-25 characters in the string.您可以做的是在字符串中声明 2-25 个字符。
Then match 1+ chars a-zA-Z and optionally match a single space and 1+ chars a-zA-Z然后匹配 1+ 字符 a-zA-Z 并可选择匹配单个空格和 1+ 字符 a-zA-Z
^(?=.{2,25}$)[a-zA-Z]+(?: [a-zA-Z]+)?$
The pattern matches:模式匹配:
^
Start of string ^
字符串开头(?=.{2,25}$)
Positive lookahead, assert 2-25 chars in the string (?=.{2,25}$)
正向前瞻,在字符串中断言 2-25 个字符[a-zA-Z]+
Match 1+ chars A-Za-z [a-zA-Z]+
匹配 1+ 个字符 A-Za-z(?: [a-zA-Z]+)?
Optionally match
and again 1+ chars from the character class$
End of string $
字符串结尾See a regex demo .查看正则表达式演示。
You could match the string with the following regular expression.您可以将字符串与以下正则表达式匹配。
^(?!.* .* )[a-zA-Z ]{2,25}$
The elements of the expression are as follows.表达式的元素如下。
^ # match beginning of string
(?!.* .* ) # negative lookahead asserts the string does not
# contain two (or more) spaces
[a-zA-Z ]{2,25} # match between 2 and 25 letters and spaces
$ # match end of string
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.