首页 > 解决方案 > 用匹配的表达式替换字符串

问题描述

我在多个文件中有以下文本Hello{Some Text},我想将其替换为Some Text. 哪里Some Text可能包括平衡的大括号{ }。例如:Hello{Some { other} Text}应替换为Some { other} Text.

sed有没有一种简单的方法可以在、或其他工具awk中实现这一点?perl

标签: regexperlawksed

解决方案


您必须选择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

推荐阅读