我正在编写一个正则表达式以类似于 shell 参数的方式解析参数,使用空格和带引号的字符串作为分隔符,以及反斜杠转义。这似乎适用于RegexPal:
(?:(["'])(?:\\(?:\\\\)?\1|\\\\|.)*?\1|(?:\\(?:\\\\)?\s|\\\\|\S)+)
这是一个更易读的版本:
(?:(["'])(?: # Match a double or single quote followed by
\\(?:\\\\)?\1 # an odd number of backslashes, then the same quote
|\\\\ # or two backslashes
|. # or anything else
)*?\1 # any number of times (lazily) followed by the same quote,
|(?: # OR
\\(?:\\\\)?\s # an odd number of backslashes, then whitespace
|\\\\ # or two backslashes
|\S # or any non-whitespace
)+ # any number of times.
)
我尝试使用 re.findall 将其放入 Python 中,但输出是无稽之谈:
>>> re.findall(
... r"(?:([\"'])(?:\\(?:\\\\)?\1|\\\\|.)*?\1|(?:\\(?:\\\\)?\s|\\\\|\S)+)",
... r'the quick brown\ fox jumps "over the" lazy\\ dog')
['', '', '', '', '"', '', '']
另一方面,RegexPal 显示了正确的结果:
[the] [quick] [brown\ fox] [jumps] ["over the"] [lazy\\] [dog]
我是否忘记以某种方式为 Python 格式化模式?或者 Python 是否以某种方式以不同的方式解释正则表达式?我不知道为什么唯一的非空匹配是双引号,并且我已经确认模式本身按其应有的方式工作。