java - 使用正则表达式提取捕获组

标签 java regex

我只是想捕获静态文本周围的字符串。我将通过例子来说明。这是我正在使用的字符串...

String idInfo = "Any text up here\n" +
                "Here is the id\n" +
                "\n" +
                "?a0 12 b5\n" +
                "&Edit Properties...\n" +
                "And any text down here";

或者用漂亮的字体......

Any text up here
Here is the id

?a0 12 b5
&Edit Properties...
And any text down here

我正在使用以下代码尝试打印 ID 号...

Pattern p = Pattern.compile("Here is the id\n\n\?[a-z0-9]{2}( [a-z0-9]{2}){2}\n&Edit Properties...);
Matcher m = p.matcher(idInfo);
String idNum = m.group(1);
System.out.println(idNum);

我想简单地输出 ID 号,所以这个例子我想要的输出是......

a0 12 b5

但是,当我运行代码时,出现“未找到匹配项”异常。我究竟做错了什么?有没有更简单、更优雅的方法来完成我的解决方案?

最佳答案

使用之前需要先让 Matcher find 匹配。因此,在访问 m.group(1); 之前调用 m.find()(或 m.matches(),具体取决于您的目标)。还要检查是否确实找到了匹配项(如果 m.find() 返回 true)以确保组 1 存在。

另一件事是表示您的正则表达式的字符串不正确。如果你想在正则表达式中转义 ? ,你需要将 \ 写成两个 "\\" 因为 \ 是String 中的特殊字符(例如用于创建 \n)也需要转义。

您在评论中指出的最后一件事是 ( [a-z0-9]{2}) 不会将匹配 a0 12 b5 放入组 1 中。为了解决这个问题,我们需要将 [a-z0-9]{2}( [a-z0-9]{2}){2} 括在括号中。

所以尝试一下

Pattern p = Pattern.compile("Here is the id\n\n\\?([a-z0-9]{2}( [a-z0-9]{2}){2})\n&Edit Properties...");
Matcher m = p.matcher(idInfo);

if (m.find()) {//or while(m.find())
    String idNum = m.group(1);
    System.out.println(idNum);
}

关于java - 使用正则表达式提取捕获组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26808266/

相关文章:

java - 如何在测试之间重新创建 EntityManagerFactory

java - Matchers.any() 用于 Mockito 中的空值

java - Recyclerview + Listadapter 中的项目不会在更新时重绘

c# - 如何用正则表达式中的特定符号替换特殊字符和空格?

javascript - 当连续单词长度为 50 个字符时插入空格

java - 非法参数异常 : Illegal base64 character 3a when decoding String value using Base64. getDecode()

java - 在 setter 中进行修剪是一种好习惯吗?

java - 使用正则表达式进行键=值对验证

java - 如何用正则表达式精确匹配单词?

php - 短语解析和趋势