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

标签 java regex

我被要求使用正则表达式捕获任何 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/

相关文章:

java - Spring 启动 : Configuration Class is simply ignored and not loaded

java - MVP 模型中 View 类中有多个演示者

java - 如何使用 Java 日历从日期中减去 X 天?

javascript - 量词不起作用

regex - 删除所有以 # 或 ; 开头的行在 Notepad++ 中

php - preg_replace 一次替换多个模式

java - java中如何区分xml和html链接

java - java中int与整数的内存大小

regex - 匹配特定长度 x 或 y

javascript - 将文本转换为链接的 Tampermonkey 脚本