这是我的输入文本
1. INTRODUCTION
This is a test document. This document lines can span multiple lines.
This is another line.
2. PROCESS
This is a test process. This is another line.
3. ANOTHER HEADING
...
我想提取主标题 1、2、3 等之间的文本。我使用此正则表达式来匹配标题 - ^[ ]{0,2}?[0-9]{0,2}\\.(.*)$
如何提取匹配之间的文本?
编辑
我尝试使用此代码 -
while(matcher.find()) {
}
如果我在这个 while 循环中向前查找下一场比赛的起始索引,它将改变匹配器的状态。如何获取使用 String.substring
之间的文本?我需要在当前匹配的结尾和下一个匹配的开头来创建子字符串。
最佳答案
How do I extract text between matches?
您的意思是介于 1. 简介和 2. 流程之间等等吗?如果是这样,如果下一行不是“标题”行,则将文本添加到某个缓冲区。如果是 header ,则将缓冲区添加到运行列表中,然后清除缓冲区。
类似于(伪代码)
List<String> content
currentContent = ""
while line = readNextLine()
if not matched header
currentContent += line
else
// found new header, clear the content and add it to the list
if currentContent != ""
content.add(currentContent)
currentContent = ""
编辑:作为一个大字符串
// Split the lines by new lines
String[] bits = yourString.split("\\n");
String currentContent = ""; // Text between headers
List<String> content = new ArrayList<String>(); // Running list of text between headers
// Loop through each line
for (String bit : bits) {
Matcher m = yourPattern.match(bit);
if (m.matches()) {
// Found a header
if (currentContent.length() != 0) {
content.add(currentContent);
currentContent = "";
}
} else {
// Not a header, just append the line
currentContent += bit;
}
}
类似的东西会起作用。我想你可以做一个复杂的多行正则表达式,但这对我来说似乎更容易
关于java - 使用java提取匹配之间的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30869113/