用于在开始和结束字符串之间提取并匹配包含结束字符串的整行的正则表达式
Regex to extract between start and end strings and match the entire line containing the end string
问题
我有一段很长的非结构化文本,我需要将文本组提取出来。
我有一个理想的开始和结束。
这是截断的非结构化文本示例:
more useless gibberish at the begininng...
separated by new lines...
START Fund Class Fund Number Fund Currency
XYZ XYZ XYZ USD
bunch of text with lots of newlines in between... Closing 11.11 1,111.11 111,111.11
more useless gibberish between the groups...
separated by new lines...
START Fund Class Fund Number Fund Currency
XYZ XYZ XYZ USD
The word START appears in the middle sometimes multiple times, but it's fine bunch of text with lots of newlines in between... Closing 22.22 2,222.22 222,222.22
more useless gibberish at the end...
separated by new lines...
我试过的
在上面的示例中,我想提取出位于 START
和 Closing
之间的 2 组文本
我已经使用正则表达式成功做到了
/(?<=START)(?s)(.*?)(?=Closing)/g
这是结果https://regex101.com/r/vo7CLx/1/
怎么了?
不幸的是,我还需要提取包含 Closing
字符串的行尾。
如果您从 regex101
link 注意到,第一场比赛中有一个 Closing 11.11 1,111.11 111,111.11
。在第二场比赛中 Closing 22.22 2,222.22 222,222.22
。
正则表达式不匹配。
有没有办法在单个正则表达式中做到这一点?这样即使带有数字的结束标记也包括在内?
(START)(?s)(.*?)(Closing)(\s+((,?\d{1,3})+.\d+))+
应该匹配你想要的一切,see here!
试试这个正则表达式:
(?s)(?<=START)(.*?Closing(?:\s*[\d.,])+)
解释:
(?s)
- 单行修饰符,这意味着正则表达式中的 .
将匹配换行符
(?<=START)
- 正向后视以找到紧接在 START
之前的位置
(.*?Closing(?:\s*[\d.,])+)
- 懒惰地匹配任何字符的 0+ 次出现,直到下一次出现单词 Closing
后跟一个序列 (?:\s*[\d.,])+
(?:\s*[\d.,])+
- 匹配出现 0 次以上的空格后跟数字或 .
或 ,
。最后的 +
意味着我们必须匹配这个子模式 1 次或更多次
你可以试试这个正则表达式,
START(.*)Closing(.*)(((.?\d{1,3})+.\d+)+.\d+.\d+.\d)\d
问题
我有一段很长的非结构化文本,我需要将文本组提取出来。
我有一个理想的开始和结束。
这是截断的非结构化文本示例:
more useless gibberish at the begininng...
separated by new lines...
START Fund Class Fund Number Fund Currency
XYZ XYZ XYZ USD
bunch of text with lots of newlines in between... Closing 11.11 1,111.11 111,111.11
more useless gibberish between the groups...
separated by new lines...
START Fund Class Fund Number Fund Currency
XYZ XYZ XYZ USD
The word START appears in the middle sometimes multiple times, but it's fine bunch of text with lots of newlines in between... Closing 22.22 2,222.22 222,222.22
more useless gibberish at the end...
separated by new lines...
我试过的
在上面的示例中,我想提取出位于 START
和 Closing
我已经使用正则表达式成功做到了
/(?<=START)(?s)(.*?)(?=Closing)/g
这是结果https://regex101.com/r/vo7CLx/1/
怎么了?
不幸的是,我还需要提取包含 Closing
字符串的行尾。
如果您从 regex101
link 注意到,第一场比赛中有一个 Closing 11.11 1,111.11 111,111.11
。在第二场比赛中 Closing 22.22 2,222.22 222,222.22
。
正则表达式不匹配。
有没有办法在单个正则表达式中做到这一点?这样即使带有数字的结束标记也包括在内?
(START)(?s)(.*?)(Closing)(\s+((,?\d{1,3})+.\d+))+
应该匹配你想要的一切,see here!
试试这个正则表达式:
(?s)(?<=START)(.*?Closing(?:\s*[\d.,])+)
解释:
(?s)
- 单行修饰符,这意味着正则表达式中的.
将匹配换行符(?<=START)
- 正向后视以找到紧接在START
之前的位置
(.*?Closing(?:\s*[\d.,])+)
- 懒惰地匹配任何字符的 0+ 次出现,直到下一次出现单词Closing
后跟一个序列(?:\s*[\d.,])+
(?:\s*[\d.,])+
- 匹配出现 0 次以上的空格后跟数字或.
或,
。最后的+
意味着我们必须匹配这个子模式 1 次或更多次
你可以试试这个正则表达式,
START(.*)Closing(.*)(((.?\d{1,3})+.\d+)+.\d+.\d+.\d)\d