我的测试字符串:
1. default, no hair, w/o glass
2. ski suit
3. swim suit
如何检测头发之前是否存在“否”或“不适合”(两者之间可能有多于一个空格)?
最终目标:
1. default, no hair, w/o glass returns False
1. default, no hair, w/o glass returns False
1. default, w/o hair, w/o glass returns False
1. default, w hair, w/o glass returns True
目标是判断是否应该使用玻璃。
我的尝试:(?<!no\s)hair
(http://rubular.com/r/PdKbmyxpGh)
你可以看到,在上面的例子中,如果有超过1个空格,那么我的正则表达式将不起作用。
答案 0 :(得分:2)
re
模块不支持可变长度(零宽度)后视。
您需要:
修正了hair
使用regex
模块
使用负向前瞻的短函数:
def re_check(s):
return re.search(r'^[^,]+,\s+(?!(?:no|w/o)\s+hair,)', s) is not None
>>> re_check('default, no hair, w/o glass')
False
>>> re_check('default, w/o hair, w/o glass')
False
>>> re_check('default, w hair, w/o glass')
True
答案 1 :(得分:1)
这是我将如何做到的:
data = ['1. default, no hair, w/o glass',
'1. default, no hair, w/o glass',
'1. default, w/o hair, w/o glass',
'1. default, w hair, w/o glass']
def hair(line):
result = re.findall('(no|w/o|w)\s+hair', line)
if result:
return result[0] == 'w':
[hair(line) for line in data]
输出:
[False, False, False, True]
如果正则表达式找不到任何内容,则返回None
。
答案 2 :(得分:1)
答案 3 :(得分:0)
答案 4 :(得分:0)
检查w hair
:
>>> for line in (
... '1. default, no hair, w/o glass',
... '1. default, no hair, w/o glass',
... '1. default, w/o hair, w/o glass',
... '1. default, w hair, w/o glass'
... ):
... print(repr(line), bool(re.search(r'w\s+hair', line)))
...
'1. default, no hair, w/o glass' False
'1. default, no hair, w/o glass' False
'1. default, w/o hair, w/o glass' False
'1. default, w hair, w/o glass' True