我搜索了与 Java 正则表达式相关的问题,并找到了有关 Pattern 和 Matcher 类的信息,以便为您提供围绕正则表达式匹配条件的文本组。
但是,我的要求不同。我希望提取由正则表达式表示的实际文本。
例子:
Input text: ABC 22. XYZ
Regular expression: (.*) [0-9]* (.*)
使用 Pattern 和 Matcher 类(或 Java 中的任何其他方式),如何获取文本“22.”?这是正则表达式代表的文本。
最佳答案
你可以试试下面的正则表达式1:
.*?(\s*\d+\.\s+).*
使用一些图形工具2,您可以看到正则表达式中的组在哪里,即:
要提取该组,在 Java 中您可以执行如下操作:
String input = "ABC 22. XYZ";
System.out.println(
input.replaceAll(".*?(\\s*\\d+\\.\\s+).*", "$1")
); // prints " 22. "
其中 $1
被替换为 group #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))
获取截图的工具是Regexper .
关于java - 使用正则表达式提取匹配的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34556734/