python - 正则表达式包含直到字符的所有内容,但忽略该字符的转义版本

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

问题出在第一组。我需要一个表达式,表示“抓取所有内容,但不包括第一个引号,但要包括转义引号”。我不知道该怎么做。

最佳答案

您可以将此正则表达式与 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\\""']

正则表达式详细信息:

  • ":匹配开头"
  • [^"\\]*:匹配 0 个或多个非 "\
  • 的任意字符
  • (?::启动非捕获组
    • \\.:匹配 \ 后跟下一个转义字符
    • [^"\\]*:匹配 0 个或多个非 "\
    • 的任意字符
  • )*:结束非捕获组,匹配该组中的 0 个或多个
  • ":匹配结束 "
  • |:或
  • \S+:匹配 1 个以上非空白字符

关于python - 正则表达式包含直到字符的所有内容,但忽略该字符的转义版本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53857669/

相关文章:

python - 选择行并替换值小于 Pandas 中特定值的列

c# - RegEx - 不解析句末的点 (.)

python - 元类错误 : type. __init__() 需要 1 个或 3 个参数

python - 编码/解码有什么区别?

python - postgresql 数据库查询后 python 脚本输出中存在未知空格

python - 是否有将 OPC-UA 扩展对象解码为可读形式的函数或方法

python - pandas 列转换

Python编写AVRO时间戳-毫秒: datum. astimezone(tz = timezones.utc)AttributeError: 'int'对象没有属性 'astimezone'

javascript - JS - 数字的正则表达式没有前导零,或者只是零

java - 使用多个可重复捕获组的正则表达式