java - 使用java提取匹配之间的文本

标签 java

这是我的输入文本

    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/

相关文章:

java - 将锁转移到 Java 中的衍生线程

java - 如何在 ScrollView 中更改按钮触摸时的颜色?

java - Selenium 网络驱动程序 : can I check if a resource (e. g。 XML 文件)已加载?

java - 更新 Map 中自定义对象的值,例如包含对象 B 列表的对象 A

不使用 element.hashCode() 的 java.util.Set 实现

java - 无法同时启动 Alfresco 和 Ephesoft 应用程序

Java反射-检查方法参数类型

java - 优化导致超时?

java - 当尝试在静态方法调用中模拟静态方法调用时,Powermock 会调用初始方法

java - 如何在 Java 中匹配一串元组?