与其尝试构造一个检测没有空格的字符串的正则表达式,不如检查确实有空格的字符串,然后反转代码中的逻辑。
请记住,如果没有找到匹配项,则re.match()
返回None
(逻辑假值),如果找到匹配项,则返回对象(逻辑真值)。用它来写这样的东西:SRE_Match
In [24]: spaces_pattern = re.compile ( r"^(\s.+|.+\s)$" )
In [27]: for s in ["Alpha", " Bravo", "Charlie ", " Delta "]:
....: if spaces_pattern.match(s):
....: print ( "%s had whitespace." % s )
....: else:
....: print ( "%s did not have whitespace." % s )
....:
Alpha did not have whitespace.
Bravo had whitespace.
Charlie had whitespace.
Delta had whitespace.
请注意使用^$
锚点来强制匹配整个输入字符串。
编辑:
这甚至根本不需要正则表达式 - 您只需要检查第一个和最后一个字符:
test_strings = ['a', ' b', 'c ', ' d ', 'e f', ' g h', ' i j', ' k l ']
for s in test_strings:
if s[0] in " \n\r\t":
print("'%s' started with whitespace." % s)
elif s[-1] in " \n\r\t":
print("'%s' ended with whitespace." % s)
else:
print("'%s' was whitespace-free." % s)
编辑2:
应该在任何地方都可以使用的正则表达式:^\S(.*\S)?
. \S
如果您的正则表达式方言不包含它,您可能需要提供与 ("anything but whitespace") 的本地等价物。
test_strings = ['a', ' b', 'c ', ' d ', 'e f', ' g h', ' i j', ' k l ']
import re
pat = re.compile("^\S(.*\S)?$")
for s in test_strings:
if pat.match(s):
print("'%s' had no whitespace." % s)
else:
print("'%s' had whitespace." % s)
请注意,这\S
是 的否定形式\s
,即\S
表示“除空格之外的任何内容”。
另请注意,长度为 1 的字符串是通过将部分匹配设为可选来计算的。(您可能会考虑使用\S.*\S
,但这会强制匹配长度至少为 2。)
'a' had no whitespace.
' b' had whitespace.
'c ' had whitespace.
' d ' had whitespace.
'e f' had no whitespace.
' g h' had whitespace.
' i j' had whitespace.
' k l ' had whitespace.