【问题标题】:Regex to detect words that are not quoted正则表达式检测未引用的单词
【发布时间】:2021-08-15 15:18:50
【问题描述】:

我有这个检测所有单词的正则表达式:

\b[^\d\W]+\b

我有这个正则表达式来检测引用的文本:

\'[^\".]*?\'|\"[^\'.]*?\"

是否有正则表达式可以检测不在引号中的单词(单引号和双引号)?

示例:

import re
a = "big mouse eats cheese? \"non-detected string\" 'non-detected string too' hello guys"
re.findall(some_regex, a)

它应该输出这个 ['big', 'mouse', 'eats', 'cheese', 'hello', 'guys']

我知道我可以使用re.sub() 来检测引用的文本,然后将其替换为空白字符串,但这就是我不想做的事情。

我还查看了此页面regex match keywords that are not in quotes 并尝试了此(^([^"]|"[^"]*")*)|(^([^']|'[^']*')*) 但它不起作用A regex to detect string not enclosed in double quotes 也尝试了此(?<![\S"])([^"\s]+)(?![\S"])|(?<![\S'])([^'\s]+)(?![\S']) 都检测到所有单词

【问题讨论】:

    标签: python-3.x regex quotes


    【解决方案1】:

    你可以使用

    import re
    a = '''big mouse eats cheese? "non-detected string" 'non-detected string too' hello guys'''
    print( [x for x in re.findall(r'''"[^"]*"|'[^']*'|\b([^\d\W]+)\b''', a) if x])
    # => ['big', 'mouse', 'eats', 'cheese', 'hello', 'guys']
    

    请参阅Python demo。列表推导用于对输出进行后处理,以删除匹配引用的子字符串产生的空项。

    这种方法有效,因为re.findall only returns the captured substrings 在正则表达式中定义捕获组时。 "[^"]*"|'[^']*' 部分匹配但不捕获单引号和双引号之间的字符串,\b([^\d\W]+)\b 部分匹配并将单词边界之间的任何一个或多个字母或下划线捕获到第 1 组中。

    【讨论】:

    • 所以如果我尝试做re.compile().search() 会成功吗?正如你所说,它有效,因为 re.findall() 行为怪异
    • @Good 只获取第一个匹配,使用re.search,但是你需要先检查是否有匹配,然后访问match.group(1)值。但是,使用这种方法,您需要使用re.findall 来获取所有匹配项,因为re.search 可能会产生空匹配项。因此,使用建议的方法获取所有匹配项,然后在必要时使用索引获取第一个非空匹配项。
    猜你喜欢
    • 2018-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 2019-02-20
    相关资源
    最近更新 更多