让我们考虑示例
<title>FileConditionCreatePage</title>
我想验证天气FileConditionCreatePage是否被HTML标记包围。.
答案 0 :(得分:1)
您可以使用此正则表达式来匹配任何与开始和结束标签匹配的标签相同的标签。
<(\w+)[^>]*>[\w\W]*?<\/\1>
^^ This back reference ensures the closing tag name is same as starting one.
var arr = ['<title>FileConditionCreatePage\nsome other text\n</title>','<title1>FileConditionCreatePage</title2>'];
for(s of arr) {
console.log(s + " --> " + /<(\w+)[^>]*>[\w\W]*?<\/\1>/.test(s));
}
相同的Java代码,
List<String> tagList = Arrays.asList("<title>FileConditionCreatePage</title>",
"<title1>FileConditionCreatePage</title2>", "<title1>FileConditionCreatePage</title2>");
Pattern p = Pattern.compile("<(\\w+)[^>]*>[\\w\\W]*?<\\/\\1>");
tagList.forEach(x -> {
Matcher m = p.matcher(x);
if (m.matches()) {
System.out.println(x + " --> Matches");
} else {
System.out.println(x + " --> Doesn't Match");
}
});
打印
<title>FileConditionCreatePage</title> --> Matches
<title1>FileConditionCreatePage</title2> --> Doesn't Match
答案 1 :(得分:0)
这是一些简单的方法(但是不能处理很多情况,例如,打开和关闭标签不同的情况)
let str= '<title>FileConditionCreatePage</title>'
let has= /<[a-z\- ]+>.*< *\/[a-z\- ]+>/i.test(str);
console.log(has);