正则表达式,用于检查字符串开头和结尾的空格

时间:2012-04-27 13:36:42

标签: python regex

这段代码不应该在开头和结尾都留有空格的字符串。出于某种原因,我对此代码有负面结果

import re
def is_match(pattern, string):
    return True if len(re.compile(pattern).findall(string)) == 1 else False
print(is_match("[^\s]+[a-zA-Z0-9]+[^\s]+", '1'))

但是,其他字符串工作正常。任何人都可以解释为什么结果是否定的,甚至提供更好的功能(python中的新手)。

6 个答案:

答案 0 :(得分:3)

您正在寻找的正则表达式是^\s|\s$

xs = ["no spaces", "  starts", "ends  ", "\t\tboth\n\n", "okay"]

import re
print [x for x in xs if re.search(r'^\s|\s$', x)]

## ['  starts', 'ends  ', '\t\tboth\n\n']

^\s.*?\s$仅匹配两端的空格:

print [x for x in xs if re.search(r'^\s.*?\s$', x, re.S)]

## ['\t\tboth\n\n']

反表达式(无起始结束空格)为^\S.*?\S$

print [x for x in xs if re.search(r'^\S.*?\S$', x, re.S)]

## ['no spaces', 'okay']

答案 1 :(得分:2)

检查字符串开头或结尾处的空格的最简单方法是不涉及正则表达式。

if test_string != test_string.strip():

答案 2 :(得分:0)

不是试图构造一个检测字符串而没有空格的正则表达式,而是更容易检查具有空格的字符串,然后反转代码中的逻辑。

请记住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.

请注意使用^$锚点强制匹配整个输入字符串。


编辑:

这根本不需要regexp - 你只需要检查第一个和最后一个字符:

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(“除空白之外的任何东西”)的本地等价物。

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.

答案 3 :(得分:0)

def is_whiteSpace(string):
    t=' ','\t','\n','\r'
    return string.startswith(t) or string.endswith(t)


print is_whiteSpace(" GO") -> True
print is_whiteSpace("GO") -> False
print is_whiteSpace("GO ") -> True
print is_whiteSpace(" GO ") -> True

答案 4 :(得分:0)

不需要花哨的正则表达式,只需使用更具可读性的方式:

>>> def is_whitespace(s):
    from string import whitespace
    return any((s[0] in whitespace, s[-1] in whitespace))

>>> map(is_whitespace, ("foo", "bar ", " baz", "\tspam\n"))
[False, True, True, True]

答案 5 :(得分:0)

ch3ka建议的一种变体:

import string
whitespace = tuple(string.whitespace)

'a '.endswith(whitespace)
## True

'a '.startswith(whitespace)
## False

'a\n'.endswith(whitespace)
## True

'a\t'.endswith(whitespace)
## True

我发现它比正则表达式更容易记住(也许将whitespace转换为元组除外)。