Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/neo4j/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 正则表达式检查某个单词是否不在另一个单词之前_Python_Regex - Fatal编程技术网

Python 正则表达式检查某个单词是否不在另一个单词之前

Python 正则表达式检查某个单词是否不在另一个单词之前,python,regex,Python,Regex,我正在尝试构建一个正则表达式,它可以让我检查某个单词前面是否有其他单词 我使用的是否定的lookback,但问题是在两者之间可能会有其他的词。这是我的测试字符串: very pure bright and nice 我想匹配bright或nice,但前提是它们前面没有very。以下是我到目前为止所做的尝试: (?<!very (?=(.{1,20})?(bright)(?=(.{1,20})?(nice))))(nice|bright) (? 但这总是与最后一句话相符 这是可能的,还是

我正在尝试构建一个正则表达式,它可以让我检查某个单词前面是否有其他单词

我使用的是否定的lookback,但问题是在两者之间可能会有其他的词。这是我的测试字符串:

very pure bright and nice
我想匹配bright或nice,但前提是它们前面没有very。以下是我到目前为止所做的尝试:

(?<!very (?=(.{1,20})?(bright)(?=(.{1,20})?(nice))))(nice|bright)
(?
但这总是与最后一句话相符

这是可能的,还是我应该试着用编程的方式来做?

这是什么?

"\w*(?<!very )(nice|bright)"

“\w*(?对我有效的解决方案是创建两个正则表达式:正数和负数。使用正数时,我只检查短语是否包含所需的单词;使用负数时,我检查某个特定单词后面是否跟有它们,然后否定否定搜索的结果:

# /usr/bin/python

import re

RE_PATTERN = re.compile(r'(bright|nice)')
RE_NEGATIVE_PATTERN = re.compile(r'very(?=.{1,30}(?:bright|nice))')


def match(string):
    pos_match = RE_PATTERN.search(string)
    neg_match = RE_NEGATIVE_PATTERN.search(string)
    matches = (bool(pos_match), not neg_match)
    return all(matches)


def test_matched():
    for s in [
        'bright',
        'nice',
        'something bright',
        'something nice',
        'bright and nice',
        'nice and bright',
    ]:
        assert match(s), s


def test_not_matched():
    for s in [
        'very pure bright and nice',
        'very good',
        'very bright',
        'very nice',
        'very something nice and bright',
        'very something nice',
        'very something bright',
    ]:
        assert not match(s), s


def main():
    test_matched()
    test_not_matched()


if __name__ == '__main__':
    main()

在同一个句子或整个文本中,单词前面不应该有“very”(非常)这个词?在同一个句子中,我希望文本块的大小较小:从一个句子到三个句子。这太容易了:)这里的困难部分是在lookback和matching group之间。