我需要一个正则表达式来满足以下要求:
>只允许使用字母,句点和空格.
>字符串的开头和结尾没有空格.
>字符串中间的空格是可以的,但不是两个连续的空格.
火柴:
"Hello world."
"Hello World. This is ok."
不匹配:
" Hello World. "
"Hello world 123."
"Hello world."
这适用于我的情况
<asp:RegularExpressionValidator ID="revDescription" runat="server"
ControlToValidate="taDescription" Display="Dynamic" ErrorMessage="Invalid Description."
Text=" "
ValidationExpression="^(?i)(?![ ])(?!.*[ ]{2})(?!.*[ ]$)[A-Z. ]{8,20}$"></asp:RegularExpressionValidator>
最佳答案 这是Python的解决方案,使用
anchors和
negative lookahead assertions来确保遵循空白规则:
regex = re.compile(
"""^ # Start of string
(?![ ]) # Assert no space at the start
(?!.*[ ]{2}) # Assert no two spaces in the middle
(?!.*[ ]$) # Assert no space at the end
[A-Z. ]{8,20} # Match 8-20 ASCII letters, dots or spaces
$ # End of string""",
re.IGNORECASE | re.VERBOSE)