我有一个字符串,其中包含多个用引号引起来的子字符串。我需要将该字符串划分为子字符串,其中每个子字符串要么是带引号的字符串,要么是带引号的字符串之间的文本,但它还需要忽略转义的引号。
示例:
'"hello" "there"'
['"hello"', '"there"']
'MACRO "hello there"'
['MACRO', '"hello there"']
'"hello there" MACRO "again, \"Steve\""'
['"hello there"', 'MACRO', '"again, \"Steve\""']
'KERN \" "Hello there, \"buddy\""'
['KERN \"', '"Hello there, \"buddy\""']
我看到了很多其他 Stackexchange 答案,但它们都只关心提取引用的字符串。我还没有找到任何可以分割整个字符串的东西。
我尝试使用 Shlex,但 Shlex 因以下字符串而失败:
c = r'KERN "Hello there, \"buddy\""'
print shlex.split(c, posix=False)
['KERN', '\\"', '"Hello there, \\"', 'buddy\\""']
“Hello there”和“buddy”应该是同一字符串的一部分。
我最接近的是:
>>> m = re.search(r'([^"]*)("?:[^"\\]|\\.*")', c)
>>> print m.groups()
('KERN ', '\\" "Hello there, \\"buddy\\""')
问题出在第一组。我需要一个表达式,表示“抓取所有内容,但不包括第一个引号,但要包括转义引号”。我不知道该怎么做。
最佳答案
您可以将此正则表达式与 findall
中的交替使用,以处理转义字符:
"[^"\\]*(?:\\.[^"\\]*)*"|\S+
代码:
>>> arr = [ r'"hello" "there"', r'MACRO "hello there"', r'"hello there" MACRO "again, \"Steve\""' ]
>>> reg = re.compile(r'"[^"\\]*(?:\\.[^"\\]*)*"|\S+')
>>> for s in arr:
... print (reg.findall(s))
...
['"hello"', '"there"']
['MACRO', '"hello there"']
['"hello there"', 'MACRO', '"again, \\"Steve\\""']
正则表达式详细信息:
"
:匹配开头"
[^"\\]*
:匹配 0 个或多个非"
和\
的任意字符
(?:
:启动非捕获组\\.
:匹配\
后跟下一个转义字符[^"\\]*
:匹配 0 个或多个非"
和\
的任意字符
)*
:结束非捕获组,匹配该组中的 0 个或多个"
:匹配结束"
|
:或\S+
:匹配 1 个以上非空白字符
关于python - 正则表达式包含直到字符的所有内容,但忽略该字符的转义版本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53857669/