我被要求使用正则表达式捕获任何 html 标记:
A. <TAG ATTRIBUTE="VALUE"/> or
B. <TAG ATTRIBUTE="VALUE"> or
C. <TAG/> or
D. <TAG> or
E. </TAG>
这是我的模式:
/** A pattern that matches a simple HTML markup. Group 1 matches
* the initial '/', if present. Group 2 matches the tag. Group
* 3 matches the attribute name, if present. Group 4 matches the
* attribute value (without quotes). Group 5 matches the closing
* '/', if present. */
public static final String HTML_P3 =
"<(/)?\\s*([a-zA-Z]+)\\s*([a-zA-Z]+)?\\s*=?\\s*\\\"?([^\\\"]+)?\\\"?\\s*(/)?>";
这是给出的测试片段:
public static void p3(String name, String markup) throws IOException {
out.println("Problem #3.");
Scanner inp = new Scanner(new FileReader(name));
while (inp.findWithinHorizon(markup, 0) != null) {
MatchResult mat = inp.match();
if (mat.group(1) != null
&& (mat.group(5) != null || mat.group(3) != null)) {
out.printf("Bad markup.%n");
continue;
}
out.printf("Tag: %s", mat.group(2));
if (mat.group(3) != null) {
out.printf(", Attribute: %s, Value: \"%s\"",
mat.group(3), mat.group(4));
}
if (mat.group(5) != null || mat.group(1) != null) {
out.print(" end");
}
out.println();
}
out.println();
}
这是输入:
This is a simple <i>mark-up</i>. Next comes
one <input value="3"/> that's closed,
followed by a list of names:
<ol color="green">
<li> Tom </li>
<li > Dick </li>
<li> Harry </li>
</ol>
正确答案应该是:
Problem #3.
Tag: i
Tag: i end
Tag: input, Attribute: value, Value: "3" end
Tag: ol, Attribute: color, Value: "green"
Tag: li
Tag: li end
Tag: li
Tag: li end
Tag: li
Tag: li end
Tag: ol end
但是,我永远无法捕捉到任何结束标签,这是我的输出:
Problem #3.
Tag: i
Tag: input, Attribute: value, Value: "3" end
Tag: ol, Attribute: color, Value: "green"
Tag: li
我试过使用 regexpal.com,我的模式匹配所有内容。有人可以点亮一些灯吗?