如何删除字符串两侧的`{{i:`和`}}`

问题描述 投票:0回答:1

我想替换所有出现的

{{i:very long text with some [special](https://google.com) nested text *here*}}

very long text with some [special](https://google.com) nested text *here*

也就是说,在伪代码中,我想从文本文件中的

<text>
获取
{{i:<text>}}

我不介意你使用哪种工具:grep、awk,...可能是一个开始。

linux replace regexp-replace
1个回答
0
投票

您可以使用 Perl 的递归正则表达式来实现您想要的结果。此正则表达式将匹配您的字符串,允许嵌套

{{i:
-
}}
对:

{{i:((?>(?:(?!{{i:|}}).)+|(?R))*)}}

它匹配:

  • {{i:
    :字面意思
    {{i:
  • ((?>(?:(?!{{i:|}}).)+|(?R))*)
    :零个或多个(在第 1 组中捕获)任一
    • (?:(?!{{i:|}}).)+
      :不在
      {{i:
      }}
      序列开头的一个或多个字符(这是一个 tempered贪婪标记);
    • (?R)
      :整个模式的递归
  • }}
    :字面意思
    }}

regex101 上的正则表达式演示

假设

test.txt

包含:

{{i:very long text with {some} [special](https://google.com) nested text *here*}} {{i:hello {{i:hola}}}}
然后你可以:

perl -pe 's/{{i:((?>(?:(?!{{i:|}}).)+|(?R))*)}}/\1/' test.txt
输出:

very long text with {some} [special](https://google.com) nested text *here* hello {{i:hola}}
    
© www.soinside.com 2019 - 2024. All rights reserved.