【发布时间】:2026-02-13 00:45:01
【问题描述】:
我正在处理文本文件,需要构建一个 perl 脚本以仅在给定文本部分(本例中为章节)的注释上运行搜索替换,以便我可以转换此模式:
Chapter 1:1 text here(Note a) more text here(Note b)
2 text here(Note c) more text here(Note d)
3 text here(Note e) more text here(Note f)
4 text here(Note g) more text here(Note h)
Chapter 2:1 text here(Note i) more text here(Note j)
2 text here(Note k) more text here(Note l)
3 text here(Note m) more text here(Note n)
4 text here(Note o) more text here(Note p)
5 text here(Note q) more text here(Note r)
6 text here(Note s) more text here(Note t)
进入这个:
Chapter 1:1 text here(Note a) more text here(Note b)
2 text here(Note c) more text here(Note d)
3 text here(Note e) more text here(Note f)
4 text here(Note g) more text here(Note h)
Chapter 2:1 text here(Note a) more text here(Note b)
2 text here(Note c) more text here(Note d)
3 text here(Note e) more text here(Note f)
4 text here(Note g) more text here(Note h)
5 text here(Note i) more text here(Note j)
6 text here(Note k) more text here(Note l)
换句话说,我需要在每个新章节的开头将每个音符的“计数器”设置为“a”。以下正则表达式匹配每一章:
(?s)^\w{1,10} \d{1,3}:\d{1,3}.+?\(Note \w\).+?(?=\w{1,10} \d{1,3}:\d{1,3})
我曾尝试使用这样的 while 循环:
my @notes = ('Note a', 'Note b', 'Note c', 'Note d');
$Count = a;
foreach my $Marker (@notes) {
$_=~s/(\\(Note\\))[a-z]/"$1".$Count++/e;
}
但是我被困住了,不可能想出一种方法来构建一个脚本,使其在每个章节划分处停止,然后重新开始直到结束。也许我使用了错误的方法?
我需要做什么才能将搜索和替换仅应用于每个章节,如上所示(即第一个正则表达式)?
任何帮助将不胜感激。 谢谢!
编辑(7 月 30 日)
两个答案都很好。我将第一个选为我最喜欢的,因为我更了解逻辑,但两者都同样有效。
现在,作为我第一个问题的推论。我怎样才能在每行之前轻松地依次包含章节名称和章节编号?像这样:
Chapter 1:1 text here(Note a) more text here(Note b)
Chapter 1:2 text here(Note c) more text here(Note d)
Chapter 1:3 text here(Note e) more text here(Note f)
Chapter 1:4 text here(Note g) more text here(Note h)
Chapter 2:1 text here(Note a) more text here(Note b)
Chapter 2:2 text here(Note c) more text here(Note d)
Chapter 2:3 text here(Note e) more text here(Note f)
Chapter 2:4 text here(Note g) more text here(Note h)
Chapter 2:5 text here(Note i) more text here(Note j)
Chapter 2:6 text here(Note k) more text here(Note l)
我需要使用变量并增加它还是有更简单的方法?
【问题讨论】:
-
发帖时不需要加
<br>标签,直接回车换行即可。