我有一组存储在 XML 文件中的正则表达式,并且我有一个必须与这些正则表达式匹配的字符串。要阅读正则表达式,我使用的是 XPath。
我的 xml 文件“ErrorPatterns.xml”如下所示:
<?xml version="1.0" encoding="windows-1252" ?>
<errors>
<pattern id="1">
<reg> ERROR:</reg>
</pattern>
<pattern id="2">
<reg> dog </reg>
</pattern>
</errors>
我的java代码如下所示:
String ab = "dog is barking";
File xmlFile = new File("ErrorPatterns.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder;
dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(new FileInputStream("ErrorPatterns.xml"));
XPath xpath = XPathFactory.newInstance().newXPath();
String expression ="/errors/pattern/reg";
NodeList nodeList = (NodeList)xpath.compile(expression).evaluate(doc,XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
String paaatern=nodeList.item(i).getFirstChild().getNodeValue().toString();
Pattern pattern2 = Pattern.compile(paaatern);
Matcher m2 = pattern2.matcher(ab);
if(m2.find())
{
System.out.println("Yaay");
}
}
运行上述代码时,它会退出而不打印“Yaay”。但是,如果不是从 xml 中读取表达式,而是像下面的代码那样直接在 Pattern 中给出,它会打印“Yaay”
NodeList nodeList = (NodeList)xpath.compile(expression).evaluate(doc,XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
Pattern pattern2 = Pattern.compile("dog");
Matcher m2 = pattern2.matcher(ab);
if(m2.find())
{
System.out.println("Yaay");
}
}
但是我从 ErrorPatterns.xml 中读取正则表达式并在项目中使用它们是不恰当的。请指导如何做。
谢谢