gpt4 book ai didi

java - 我的正则表达式模式有什么问题?

转载 作者:行者123 更新时间:2023-11-30 11:26:51 25 4
gpt4 key购买 nike

我被要求使用正则表达式捕获任何 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,我的模式匹配所有内容。有人可以放一些灯吗?

最佳答案

首先,由于您正在尝试为 Java 编写正则表达式模式,因此请使用 java regex tester .

我不是 Java 专家,但我不确定您是否需要对双引号进行三重转义。

您的模式中的一个问题是您使用了连续的问号:([a-zA-Z]+)?\\s*=?\\s*\"?([^\"]+)?\"? 而不是将所有内容分组到非捕获组中:

(?:([a-zA-Z]+)\\s*=\\s*\"([^\"]+)\")?

(如果没有属性,则没有相等,没有引号,也没有值)

你可以试试这个:(写成java字符串)

"(?i)<(/)?([a-z1-6]+)(?:\\s+([a-z]+)\\s*=\\s*\"([^\"]*+)\"\\s*)?(/)?>"

关于java - 我的正则表达式模式有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19602158/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com