正则表达式不允许在字符串中间出现两个连续的空格 [英] Regular Expression to disallow two consecutive white spaces in the middle of a string
本文介绍了正则表达式不允许在字符串中间出现两个连续的空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要一个正则表达式来满足以下要求:
I need a regex to meet the following requirements:
- 仅允许使用字母,句点和空格.
- 字符串的开头和结尾没有空格.
- 字符串中间的空格可以,但是不能连续两个空格.
比赛:
"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中的解决方案,使用锚和否定超前断言,以确保遵循空白规则:
Here's a solution in Python, using anchors and negative lookahead assertions to make sure the whitespace rules are followed:
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)
这篇关于正则表达式不允许在字符串中间出现两个连续的空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文