java - 使用正则表达式提取匹配的字符串

标签 java regex

我搜索了与 Java 正则表达式相关的问题,并找到了有关 Pattern 和 Matcher 类的信息,以便为您提供围绕正则表达式匹配条件的文本组。

但是,我的要求不同。我希望提取由正则表达式表示的实际文本。

例子:

Input text: ABC 22. XYZ
Regular expression: (.*) [0-9]* (.*)

使用 Pattern 和 Matcher 类(或 Java 中的任何其他方式),如何获取文本“22.”?这是正则表达式代表的文本。

最佳答案

你可以试试下面的正则表达式1:

.*?(\s*\d+\.\s+).*

使用一些图形工具2,您可以看到正则表达式中的组在哪里,即:

Imgur

要提取该组,在 Java 中您可以执行如下操作:

String input = "ABC 22. XYZ";

System.out.println(
    input.replaceAll(".*?(\\s*\\d+\\.\\s+).*", "$1")
);  // prints " 22. "

其中 $1 被替换为 group #1


注释

  1. 正则表达式的解释:

    NODE         EXPLANATION
    ------------------------------------------------------------------
      .*?        any character except \n (0 or more times
                 (matching the least amount possible))
    ------------------------------------------------------------------
      (          group and capture to \1:
    ------------------------------------------------------------------
        \s*        whitespace (\n, \r, \t, \f, and " ") (0
                   or more times (matching the most amount
                   possible))
    ------------------------------------------------------------------
        \d+        digits (0-9) (1 or more times (matching
                   the most amount possible))
    ------------------------------------------------------------------
        \.         '.'
    ------------------------------------------------------------------
        \s+        whitespace (\n, \r, \t, \f, and " ") (1
                   or more times (matching the most amount
                   possible))
    ------------------------------------------------------------------
      )          end of \1
    ------------------------------------------------------------------
      .*         any character except \n (0 or more times
                 (matching the most amount possible))
    
  2. 获取截图的工具是Regexper .

关于java - 使用正则表达式提取匹配的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34556734/

相关文章:

java - 在面向读写 block 的过程中,Spring Batch 在哪里提交?

java - while 循环中两个条件之间的差异

regex - 如何停止搜索单词(regex、grep)?

javascript - 如何用不同的结果替换文本中所有相同的字符/字符串?

正则表达式在jmeter中提取两个字符串文本

java - 在同一虚拟机内切换 WAL 使用?

java - 我们必须关闭 session 对象吗?

java - 在 Intellij-IDEA 调试器中杀死 java 线程

c++ - 在 C++ 中的正则表达式中捕获组

Python 正则表达式匹配或标记化