正则表达式不替换匹配的最后一次出现 [英] Regex not replacing the last occurrence of a match

查看:62
本文介绍了正则表达式不替换匹配的最后一次出现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下文本布局:

Heading
Chapter 1:1 This is text
2 This is more text
3 This is more text
4 This is more text
5 This is more text
6 This is more text
7 This is more text
8 This is more text
9 This is more text
10 This is more text
11 This is more text
12 This is more text
13 This is more text
14 This is moret text 
15 This is more text
Heading    
Chapter 2:1 This is text
2 This is more text...

并且我试图在标题之后添加第一章参考和该章中的最后一个,写在括号中.像这样:

and I am trying to add the first Chapter reference and the last one in that Chapter right after the Heading, written in parentheses. Like so:

Heading (Chapter 1:1-15)
Chapter 1:1 This is text
2 This is more text
3 This is more text
4 This is more text
5 This is more text
6 This is more text
7 This is more text
8 This is more text
9 This is more text
10 This is more text
11 This is more text
12 This is more text
13 This is more text
14 This is moret text 
15 This is more text

到目前为止我已经想出了这个正则表达式:

I've come up with this regular expression so far:

~s/(?s)(Heading)\r(^\d*\w+\s*\d+:\d+|\d+:\d+)(.*?)(\d+)(.*?\r)(?=Heading)/\1 (\2-\4)\r\2\3\4\5/g;

但这是在第 1:1 章之后的第一个数字(即2",标题(第 1:1-2 章)"),而不是最后一个(15",如标题(第 1 章)")1:1-15)").有人可以告诉我正则表达式有什么问题吗?谢谢!

but this is grabbing the first number right after Chapter 1:1 (i.e. "2", "Heading (Chapter 1:1-2)"), instead of the last one ("15" as in "Heading (Chapter 1:1-15)"). Could someone please tell me what's wrong with the regex? Thank you!

推荐答案

编辑更新问题

这是一个带有解释的正则表达式,可以解决您的问题.http://codepad.org/mSIYCw4R

Here's a regex with explanation that will solve your problem. http://codepad.org/mSIYCw4R

~s/
((?:^|\n)Heading)   #Capture Heading into group 1.
                    #We can't use lookbehind because of (?:^|\n)
(?=                 #A lookahead, but don't capture.
  \nChapter\s       #Find the Chapter text.
  (\d+:\d+)         #Get the first chapter text. and store in group 2
  .*                #Capture the rest of the Chapter line.
  (?:\n(\d+).+)+    #Capture every chapter line.
                    #The last captured chapter number gets stored into group 3.
)
/$1 (Chapter $2-$3)/gx;

这篇关于正则表达式不替换匹配的最后一次出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆