regex - 用匹配的表达式替换字符串
问题描述
我在多个文件中有以下文本Hello{Some Text}
,我想将其替换为Some Text
. 哪里Some Text
可能包括平衡的大括号{ }
。例如:Hello{Some { other} Text}
应替换为Some { other} Text
.
sed
有没有一种简单的方法可以在、或其他工具awk
中实现这一点?perl
解决方案
您必须选择perl
,因为它支持子例程调用。递归匹配{[^{}]*}
应该连续发生,如果找到不平衡的大括号,则应该失败。下面的正则表达式完成了这项工作:
Hello({((?:[^{}]*+|(?1))*)})
在此处查看现场演示
注意:它在面对转义大括号时失败。
珀尔:
$ echo 'Hello{Some { other} Text}' | perl -pe 's~Hello({((?:[^{}]*+|(?1))*)})~$2~g'
Some { other} Text
正则表达式分解:
Hello # Match `Hello`
( # Start of 1st capturing group
{ # Match `{`
( # Start of 2nd capturing group
(?: # Start of non-capturing group
[^{}]*+ # Match anything but `{` or `}` possessively
| # Or
(?1) # Recurs first group
)* # End of NCG, repeat as much as possible
) # End of 2nd CP
} # Match `}`
) # End of 1st CP
推荐阅读
- python - 如何在 Django Python 中加入 3 个表
- javascript - 单击按钮时的状态 400
- reactjs - TypeScript/React - 如何让函数接受通用组件类型?
- html - CSS 过渡 - 我希望黑色边框在单击两个选项中的任何一个时平滑地左右滑动
- javascript - 如何通过键:值对将数组中的对象相互比较?
- ios - 表达式“[”的类型在没有更多上下文的情况下是模棱两可的
- android - 什么是 AVC 阻止列表?
- function - Pine 脚本中的函数与中断
- python - 使用 pymysql 在 Mysql 的表中没有插入数据
- java - 单击不同的图像,它会更改 idImage(int 0 到 9)bottomSheetDialog