正则表达式,包括一个字符之前的所有内容,但忽略该字符的转义版本

时间:2018-12-19 19:03:22

标签: python regex python-2.x

我有一个包含引号的多个子字符串的字符串。我需要将该字符串分成多个子字符串,其中每个子字符串要么是带引号的字符串,要么是带引号的字符串之间的文本,但是它还需要忽略转义的引号。

示例:

'"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\\""')

问题是第一组。我需要一个表达式,说:“抓住所有内容,但不包括第一个引号,但包括转义的引号”。我不知道该怎么做。

1 个答案:

答案 0 :(得分:0)

您可以将此正则表达式与findall中的交替使用来处理转义字符:

"[^"\\]*(?:\\.[^"\\]*)*"|\S+

RegEx Demo

代码:

>>> 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\\""']

RegEx详细信息:

  • ":比赛开始"
  • [^"\\]*:匹配0个或多个非"\以外的字符
  • (?::启动非捕获组
    • \\.:匹配\,后跟下一个转义字符
    • [^"\\]*:匹配0个或多个非"\以外的字符
  • )*:结束非捕获组,匹配该组的0个或更多
  • ":比赛闭幕"
  • |:或
  • \S+:匹配1个以上非空格字符