我从文件中有此文本,我想使用模式匹配获取值:
<!--
@author: batman
@description: 100000
-->
我使用此代码在 XML 文件中查找注释并使用模式匹配获取值:
XMLStreamReader xr = XMLInputFactory.newInstance().createXMLStreamReader(new FileInputStream(file));
Pattern pattern = Pattern.compile("@(?<key>([\\w]+)?): (?<value>(.+)?)");
while (xr.hasNext())
{
if (xr.next() == XMLStreamConstants.COMMENT) {
String comment = xr.getText();
Matcher matcher = pattern.matcher(comment);
if(!matcher.matches()){
continue;
}
.....
}
当我运行代码时出现错误:
persistence-configuration.xsd (No such file or directory)
at [row,col {unknown-source}]: [4,69]
但是当我删除 matcher.matches()
时如果 xr
我得到了几次迭代因为我在 XML 文件中有几条注释。
这个想法是只获取正确匹配的评论并跳过其余评论。你知道为什么代码不能正常工作吗?
我也尝试过 "@(?<key>[\\w]+): (?<value>.*)"
但我又遇到了同样的问题。
最佳答案
你的输入源真的存在吗?您收到的异常提示存在文件问题。
Matcher.matches()
测试 String
与整个模式的完全确认。输入序列的所有字符都需要被消耗。因此,如果您的行以空格(制表符、空格...)开头,那么如果您使用 matches
,您的匹配器可能无法匹配。
您正在寻找matcher.find()
,可以这样使用:
Pattern myPattern = Pattern.compile("somePattern");
Matcher matcher = pattern.matcher("someInput");
while (matcher.find()) {
// this is where you can check what you found...
}
此外,您可能想检查流以哪些 block 提供元素。他们真的是按顺序来的吗?
关于java - matches() 方法的模式匹配无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61868971/