如何在 python 中使用 \K 表示正则表达式?

Yu *_* Gu 9 python regex python-3.x

\K意味着重置匹配的开始,当不支持复杂的lookbehind(即,它不允许+和*用于lookbehind)时,这非常有用。它很好地满足了我的需求,但是,当我尝试在 python 中使用它时,它报告bad escape \K. 以下是我的Python代码:

re.sub(r'\[\n[ ]+\d+, ?\n[ ]+\K\d+(?=, ?\n[ ]+(?:true|false)\n[ ]+\])', '__table1.column__', content)
Run Code Online (Sandbox Code Playgroud)

The*_*ird 8

您可以改用 2 个捕获组:

(\[\n[ ]+\d+, ?\n[ ]+)\d+(, ?\n[ ]+(?:true|false)\n[ ]+\])
Run Code Online (Sandbox Code Playgroud)

Python 演示| 正则表达式演示

在替换使用中:

\1__table1.column__\2
Run Code Online (Sandbox Code Playgroud)

例如

re.sub(
    r'(\[\n[ ]+\d+, ?\n[ ]+)\d+(, ?\n[ ]+(?:true|false)\n[ ]+\])',
    r'\1__table1.column__\2',
    content
)
Run Code Online (Sandbox Code Playgroud)

  • 谢谢!这对我来说非常有效。所以我猜想 python 中的正则表达式没有对 \K 的直接支持? (2认同)