【问题标题】:Negative Lookahead & Negative Lookbehind to Exclude Alphanumeric characters surrounded by Quotation marks用于排除被引号括起来的字母数字字符的负向预读和负向预读
【发布时间】:2021-04-11 17:14:28
【问题描述】:

我正在尝试创建一个区分变量名和字符串的正则表达式。字符串用引号括起来,变量名由字母数字字符和下划线组成。我正在尝试匹配整行中的子字符串,因此由于^ 锚定到行首,$ 锚定到行尾,因此我避免了这两个。

我排除某些变量名称的问题涉及我的否定前瞻。它只适用于一个字符,我希望这个规则也适用于子字符串的开头。

例如:

(?<!")([A-Za-z_]+[A-Za-z0-9_]*)(?!")

如果这个正则表达式被赋予字符串Hello there,它将返回两个匹配项,Hellothere。这是意料之中的。但是,如果我在子字符串的末尾添加引号,则直到带有以下引号的字符之前的每个字符仍将作为匹配项返回。例如,Hello there" 将匹配 Hellother 与此正则表达式。考虑到我在中组比赛中的第一个系列赛,我想这也是有道理的。

我的分组有什么问题?

【问题讨论】:

  • 所以你想要(?&lt;!")\b([A-Za-z_]+[A-Za-z0-9_]*)\b(?!")
  • 这肯定更接近我想要的。提供字符串"Hello there how are you" 将排除"Helloyou",但它将匹配therehoware。我正在考虑的涉及某种递归,以排除引号之间或引号旁边的所有内容。
  • @WiktorStribiżew 基本上是这个解决方案的逆regex101.com/r/W4qMDG/1
  • 当你说“逆”时,首先想到的是分裂。编程语言是什么?
  • 这是否意味着您要提取这里所有的绿色单词 - regex101.com/r/u4cGMS/1re.findall(r''''[^'\\]*(?:\\.[^'\\]*)*'|"[^"\\]*(?:\\.[^"\\]*)*"|(\w+)''', text)

标签: regex


【解决方案1】:

你可以使用

r"""'[^'\\]*(?:\\.[^'\\]*)*'|"[^"\\]*(?:\\.[^"\\]*)*"|\b([A-Za-z_]+[A-Za-z0-9_]*)\b"""

请参阅regex demo

详情

  • '[^'\\]*(?:\\.[^'\\]*)*' - 单引号字符串文字
  • | - 或
  • "[^"\\]*(?:\\.[^"\\]*)*" - 双引号字符串文字
  • | - 或
  • \b([A-Za-z_]+[A-Za-z0-9_]*)\b - 一个或多个字母或下划线,然后是零个或多个字母数字字符。

Python demo

import re
rx = r"""'[^'\\]*(?:\\.[^'\\]*)*'|"[^"\\]*(?:\\.[^"\\]*)*"|\b([A-Za-z_]+[A-Za-z0-9_]*)\b"""
text = r"""
Hello Colm "This is a test\\\\"
"This is also an NL test"
'And this has  an escaped quote don\'t  in it ' Blue Boy
"This has a single quote ' but doesn\' end the quote as it started with double quotes"

"line spanning with escaped quote at the end of a line\"
"

"Foo Bar" "Another Value" something else
"""
print(list(filter(None, re.findall(rx, text))))
# => ['Hello', 'Colm', 'Blue', 'Boy', 'something', 'else']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-03
    • 1970-01-01
    相关资源
    最近更新 更多