如何在python中的lookbehind regex中使用星号?

2024-05-18 22:28:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我的测试字符串:

1. default, no   hair, w/o glass
2. ski suit
3. swim suit

如何检测头发前面是否有“no”或“w/o”(中间可能有1个以上的空格)?在

最终目标:

^{pr2}$

其目的是判断是否应该使用玻璃。在

我的尝试:(?<!no\s)hairhttp://rubular.com/r/PdKbmyxpGh

在上面的例子中可以看到,如果有超过1个空格,那么我的正则表达式就不能工作了。在


Tags: no字符串目的httpdefault空格suit玻璃
3条回答

Look behind不支持可变宽度。在

向前看确实支持可变宽度。您可以:

^(?!.*(?:(?:\bno\b)|(?:\bw\/o\b)\s+hair))(^.*$)

Demo

我可以这样做:

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]

输出:

^{pr2}$

如果regex没有找到任何内容,则返回None。在

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

相关问题 更多 >

    热门问题