正则表达式在开头和结尾处都没有空格 [英] RegEx for no whitespace at the beginning and end
问题描述
我想设计一个表达式,不允许在字符串的开头和结尾处留空格,而在字符串的中间留空.
I want to design an expression for not allowing whitespace at the beginning and at the end of a string, but allowing in the middle of the string.
我尝试过的正则表达式是:
The regex I've tried is this:
\^[^\s][a-z\sA-Z\s0-9\s-()][^\s$]\
推荐答案
这应该有效:
^[^\s]+(\s+[^\s]+)*$
如果要包括字符限制:
^[-a-zA-Z0-9-()]+(\s+[-a-zA-Z0-9-()]+)*$
说明:
开头^
和结尾$
表示字符串.
the starting ^
and ending $
denotes the string.
考虑到我给出的第一个正则表达式,[^\s]+
表示at least one not whitespace
,而\s+
表示at least one white space
.还要注意,括号()
将第二个和第三个片段和*
分组在一起,最后是zero or more of this group
.
因此,如果您看一下,表达式为: begins with at least one non whitespace and ends with any number of groups of at least one whitespace followed by at least one non whitespace
.
considering the first regex I gave, [^\s]+
means at least one not whitespace
and \s+
means at least one white space
. Note also that parentheses ()
groups together the second and third fragments and *
at the end means zero or more of this group
.
So, if you take a look, the expression is: begins with at least one non whitespace and ends with any number of groups of at least one whitespace followed by at least one non whitespace
.
例如,如果输入为"A",则表示匹配,因为它与begins with at least one non whitespace
条件匹配.输入"AA"匹配的原因相同.输入'A A'也匹配,因为第一个A匹配at least one not whitespace
条件,然后'A'匹配any number of groups of at least one whitespace followed by at least one non whitespace
.
For example if the input is 'A' then it matches, because it matches with the begins with at least one non whitespace
condition. The input 'AA' matches for the same reason. The input 'A A' matches also because the first A matches for the at least one not whitespace
condition, then the ' A' matches for the any number of groups of at least one whitespace followed by at least one non whitespace
.
'A'不匹配,因为不满足begins with at least one non whitespace
条件.由于不满足ends with any number of groups of at least one whitespace followed by at least one non whitespace
条件,因此'A'不匹配.
' A' does not match because the begins with at least one non whitespace
condition is not satisfied. 'A ' does not matches because the ends with any number of groups of at least one whitespace followed by at least one non whitespace
condition is not satisfied.
如果要限制在开始和结束处要接受的字符,请参阅第二个正则表达式.我在开头和结尾都允许使用a-z,A-Z,0-9和().仅允许这些.
If you want to restrict which characters to accept at the beginning and end, see the second regex. I have allowed a-z, A-Z, 0-9 and () at beginning and end. Only these are allowed.
正则表达式游乐场: http://www.regexr.com/
这篇关于正则表达式在开头和结尾处都没有空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!