我只是想捕获静态文本周围的字符串。我将通过例子来说明。这是我正在使用的字符串...
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/