gpt4 book ai didi

java - 验证标签是否在另一个 Java 正则表达式中

转载 作者:行者123 更新时间:2023-12-02 02:10:10 25 4
gpt4 key购买 nike

我必须验证 <tagN> (其中 N 是数字)位于标签 <p></p> 内。万一它不在<p>里面,我必须补充一下。否则就可以了。我有所有这些情况,我尝试了一段时间,但找不到覆盖所有情况的模式:

import java.util.regex.*;


public class Main {

static String case1 = "<p><tag1></p>"; // Output: Group 1: <p>. Group 2: <tag1>. Group 3: </p>
static String case2 = "<tag1>"; // Output: Group 1: null. Group 2: <tag1>. Group 3: null
static String case3 = "<p> <tag1> </p>"; // Output: Group 1: <p>. Group 2: <tag1>. Group 3: </p>
static String case4 = "<><tag1></p>"; // NO OK. Output: Group 1: null. Group 2: <tag1>. Group 3: </p>
static String case5 = "<p><tag1><tag2></p>"; // Output: Group 1: <p>. Group 2: <tag1><tag2>. Group 3: </p>
static String case6 = "<p> <tag1> <tag2> </p>"; // Output: Group 1: <p>. Group 2: <tag1><tag2>. Group 3: </p>
static String case7 = "<p> <tag1>\n\n<tag2> </p>"; // Output: Group 1: <p>. Group 2: <tag1><tag2>. Group 3: </p>
static String case8 = "<p>\n\n <tag1>\n\n<tag2> \n</p>"; // Output: Group 1: <p>. Group 2: <tag1><tag2>. Group 3: </p>
static String case9 = " <tag1> <tag2> "; // Output: Group 1: null. Group 2: <tag1><tag2>. Group 3: null
static String case10 = " <tag1>\n\n<tag2> "; // Output: Group 1: null. Group 2: <tag1><tag2>. Group 3: null
static String case11 = "\n\n <tag1>\n\n<tag2> \n"; // Output: Group 1: null. Group 2: <tag1><tag2>. Group 3: null

public static void main(String[] args) {
//String patternString = "(<p>\\s*)*([<tag\\d+>\\s*]+)(\\s*</p>)*"; // Works only for cases 2, 9, 10 and 11
//String patternString = "(<p>\\s*)*(<tag\\d+>+)(\\s*</p>)*"; // Works only for cases 1, 2, 3, 4
Pattern pattern = Pattern.compile(patternString);
Matcher matcher = pattern.matcher(case5);

while (matcher.find()) {
System.out.println("Group 0: " + matcher.group(0));
System.out.println("Group 1: " + matcher.group(1));
System.out.println("Group 2: " + matcher.group(2));
System.out.println("Group 3: " + matcher.group(3));

// The idea here is add tag <p> when group 1 is null and tag </p> when group 3 is null
}

}
}

基本上,我尝试分成 3 组:

  • 第 1 组:标签 (<p>\\s*)* // \\s is for whitespaces/tab/newlines in case it finds 0 or more

  • 第 2 组:尝试重复 tag1、tag2 等,这就是包含在 []+ 中的原因但似乎不行

  • 第 3 组:标签 (\\s*</p>)* // \\s is for whitespaces/tab/newlines in case it finds 0 or more

有什么想法吗?谢谢

最佳答案

最后,我不得不替换 <tag1>通过 ~tag1~第一个表达式就OK了。

String patternString = "(<p>\\s*)*([~tag\\d+~\\s*]+)(\\s*</p>)*";

通过这两个更改,我得到了预期的结果。谢谢

关于java - 验证标签是否在另一个 Java 正则表达式中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57332487/

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