regex - 如何使用 sed 在两个模式之间插入 ']['?
问题描述
我编写了一个 Bash 脚本,它利用正则表达式来处理我用 Markdown 编写的文本文件,以便可以将它们编译为 .html 文件。此处理的一项任务旨在更改如下所示的懒惰书写文本:
Verkle 树正在成为以太坊即将进行的扩展升级的重要组成部分。它们提供与 Merkle 树相同的功能:[您可以将大量数据放入 Verkle 树3],并对任何单个或一组数据进行简短证明(“见证”),这些数据可以由只有树根的人验证。
转换成编译时将显示链接的文本:
Verkle 树正在成为以太坊即将进行的扩展升级的重要组成部分。它们具有与 Merkle 树相同的功能:[您可以将大量数据放入 Verkle 树][3],并对任何单个或一组数据进行简短证明(“见证”)这可以由只有树根的人来验证。
换句话说,我想替换[text that begins with a letter and consists of words, letters and punctuation. The text ends with a positive integer smaller than 100 int]
为[text that begins with a letter and consists of words, letters and punctuation.The text ends with a bracket][int]
以下是用于执行我上面描述的任务的代码片段:
sed -i -E 's/(\[[a-zA-Z]{2,2}[\s\S]{1,100})(\[0-9]{1,2}\])/\1\][\2/g' file.txt;
该代码旨在使我免于编写额外的 '][' 并且会自动为我完成。该代码不起作用,我不知道为什么。
解决方案
您编写的正则表达式与PCRE兼容,但您需要一个POSIX表达式,因为sed
仅支持 POSIX BRE 或 ERE。
您可以使用
sed -i -E 's/(\[[[:alpha:]]{2}([^][]*[^0-9])?)([0-9]{1,2}])/\1][\3/g' file
查看在线演示:
s='Verkle trees are shaping up to be an important part of Ethereum'"'"'s upcoming scaling upgrades. They serve the same function as Merkle trees: [you can put a large amount of data into a Verkle tree3], and make a short proof ("witness") of any single piece, or set of pieces, of that data that can be verified by someone who only has the root of the tree.'
sed -E 's/(\[[[:alpha:]]{2}([^][]*[^0-9])?)([0-9]{1,2}])/\1][\3/g' <<< "$s"
输出:
Verkle trees are shaping up to be an important part of Ethereum's upcoming scaling upgrades. They serve the same function as Merkle trees: [you can put a large amount of data into a Verkle tree][3], and make a short proof ("witness") of any single piece, or set of pieces, of that data that can be verified by someone who only has the root of the tree.
详情:
(\[[[:alpha:]]{2}([^][]*[^0-9])?)
- 第 1 组 (\1
):\[
- 一个[
字符[[:alpha:]]{2}
- 两个字母([^][]*[^0-9])?
- 一个可选的零个或多个字符序列,除了[
and]
然后是一个非数字字符
([0-9]{1,2}])
- 第 3 组 (\3
):一位或两位数。
替换为\1][\3
, Group 1 + ][
+ Group 3 值连接(不使用 Group 2,因为它仅用于匹配 Group 1 内的可选部分,并且sed
POSIX 正则表达式不支持非捕获组)。
推荐阅读
- sed - SED:如何替换文本块(
至 ) 在一个文件中包含另一个文件的内容? - javascript - 如何设置 JSON ISO-8601 日期时间格式时区
- javascript - 在参数中使用解构时未捕获的 typeError
- reactjs - 如何在提交表单之前编辑表单 json 数据?
- python - 我需要一些帮助来理解这个错误
- reactjs - 注销时重置 Apollo 存储和经过身份验证的查询
- python - 使用 nginx 作为我的服务器并运行一个简单的烧瓶应用程序。我可以配置 nginx 来提供烧瓶和非烧瓶网址吗?
- python - 我的 For 循环只经过一次。(我正在使用 Python)
- tensorflow - ubantu18.04 tensorflow2.2.0 和 CUDA=10.1 的服务器有 4 个 GPU,但是运行 yolo-keras 程序时只使用了一个 GPU
- java - Java Zookeeper API 奇怪的 ZNode 行为。无法正确删除 ZNode。它有意想不到的结果