问题描述
我想设计一个表达式,不允许在字符串的开头和结尾有空格,但允许在字符串中间.
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]+)*$
如果您想包含字符限制:
If you want to include character restrictions:
^[-a-zA-Z0-9-()]+(\s+[-a-zA-Z0-9-()]+)*$
说明:
开头的^
和结尾的$
表示字符串.
the starting ^
and ending $
denotes the string.
考虑我给出的第一个正则表达式,[^\s]+
表示 至少一个不是空格
,\s+
表示 至少一个空格
.另请注意,括号 ()
将第二个和第三个片段组合在一起,最后的 *
表示 该组的零个或多个
.所以,如果你看一看,表达式是:以至少一个非空格开始,以任意数量的至少一个空格后跟至少一个非空格的组结束
.
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' 匹配.输入AA"也匹配,因为第一个 A 匹配 至少一个非空格
条件,然后A"匹配 任意数量的至少一个空格的组,后跟至少一个非空格
.
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' 不匹配,因为 以至少一个非空格开头
条件不满足.'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/
这篇关于正则表达式在开头和结尾没有空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!