您好,我在 Java 中使用正则表达式时遇到问题。
我正在尝试解析这个:
*whatever string*
<AttributeDesignator AttributeId="MyIDToParse"
DataType="http://www.w3.org/2001/XMLSchema#string"
Category="theCategoryIWantToParse"
MustBePresent="false"
/>
*whatever string that may contain the same regular expression*
使用此代码(模式+匹配器)
Pattern regex = Pattern.compile("AttributeDesignator +AttributeId=\"(.+)\" +.*Category=\"(.+)", Pattern.DOTALL);
Matcher matcher = regex.matcher(xml);
while (matcher.find()) {
String ID = matcher.group(1);
String Category = matcher.group(2);
输出如下:
第 1 组:
MyIDToParse"
DataType="http://www.w3.org/2001/XMLSchema#string"
Category="theCategoryIWantToParse"
MustBePresent="false"
/>
*whatever string that may contain the same regular expression*
组2:
theCategoryIWantToParse"
MustBePresent="false"
/>
*whatever string that may contain the same regular expression*
我觉得这很简单,但我找不到我做错的地方.. 当我在网站中使用正则表达式来测试它们时,它可以正常工作并突出显示 xml 条目中的正确表达式。
最佳答案
尝试使用非贪婪正则表达式。
Pattern regex = Pattern.compile("AttributeDesignator AttributeId=\"(.+?)\".*Category=\"(.+?)\"", Pattern.DOTALL);
关于java - 将 XML 的正则表达式部分与 java 匹配时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31805483/