python - 正则表达式仅在花括号之间替换模式
问题描述
我试图用后面的字符替换 a':'
或 a ,直到双花括号出现在双花括号之间时才出现空字符串。'|'
}}
''
例子:
s = "This is an {{example_string:default_or_none}} or {{some_variable|yeah}} of what I want and this should:be untouched"
应该变成:
"This is an {{example_string}} or {{some_variable}} of what I want and this should:be untouched"
我试过这个:
re.sub(r'(?<=\{\{\w*)[:\|](?=\}\})', '', s)
但它不起作用。我也得到一个错误:
error: look-behind requires fixed-width pattern
解决方案
即使在花括号中有多个:
或|
在花括号内的情况下,以下内容也适用:
import re
s = "This is an {{example_string:default_or_none|other|filter:whatever}} or {{some_variable|yeah}} of what I want and this should:be untouched"
result = re.sub('\{\{(\w+).*?\}\}', r'{{\1}}', s)
print(result)
输出
This is an {{example_string}} or {{some_variable}} of what I want and this should:be untouched
推荐阅读
- websocket - WebSocket:失败:WebSocket 握手期间出错:net::ERR_INVALID_HTTP_RESPONSE
- node.js - React Native 使用 fetch 向 Node.js 服务器发送数据
- jhipster - 带有 Easticsearch 的 v5.0.1 的新 JHipster 应用程序生成(HTTP 代码 500)服务器错误
- webpack - 将 Sass 与 Vue-loader webpack 堆栈正确集成
- html - CSS页脚网格响应
- angularjs - AngularJS $http.post 不向 Django REST 后端发送数据
- java - 重启后Hbase数据被删除
- azure-sql-database - 无法导出 Azure SQL 数据库
- r - 直方图中的条数 - R
- python - 从另一个字典中删除重复值