javascript 正则表达式匹配打开和关闭的 html 标签

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21152404/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 20:14:00  来源:igfitidea点击:

Regular Expression to match open and closed html tags

javascriptregex

提问by CodeCrack

I want to come up with Regular Expression to return true if the a closed html tag is matched with an open one in specific text that gets passed in JavaScript. If there is an unmatched tag, it should return false;

如果关闭的 html 标记与在 JavaScript 中传递的特定文本中的打开标记匹配,我想提出正则表达式以返回 true。如果存在不匹配的标签,则应返回 false;

For example, if the following text is passed "<div>Test</div>"it should return true but if the following text gets passed "<div>Test</div><div>Boom"it should return false

例如,如果传递了以下文本"<div>Test</div>",则应返回 true 但如果传递以下文本"<div>Test</div><div>Boom",则应返回 false

I can only get it to match the first div tags to return true with the following expression

我只能让它匹配第一个 div 标签以使用以下表达式返回 true

    var text = "<div>Test</div>; 
    var text2 = "<div>Test</div><div>; 
    var regex = /[^<>]*<(\w+)(?:(?:\s+\w+(?:\s*=\s*(?:".*?"|'.*?'|[^'">\s]+))?)+\s*|\s*)>[^<>]*<\/+\s*>[^<>]*|[^<>]*<\w+(?:(?:\s+\w+(?:\s*=\s*(?:".*?"|'.*?'|[^'">\s]+))?)+\s*|\s*)\/>[^<>]*|<!--.*?-->|^[^<>]+$/;
    var match = regex.test(text);
    console.log(match); // true
    var match = regex.test(text2);
    console.log(match2); // still true should be false

How can I fix it so it functions the way I want it to.

我该如何修复它才能让它按照我想要的方式运行。

回答by Stephan

The testmethod returns true for match2because it has found a match.

test方法返回 true ,match2因为它找到了匹配项

In order to fix it, change your regex this way:

为了修复它,请以这种方式更改您的正则表达式:

^(?:<(\w+)(?:(?:\s+\w+(?:\s*=\s*(?:".*?"|'.*?'|[^'">\s]+))?)+\s*|\s*)>[^<>]*<\/+\s*>|<\w+(?:(?:\s+\w+(?:\s*=\s*(?:".*?"|'.*?'|[^'">\s]+))?)+\s*|\s*)\/>|<!--.*?-->|[^<>]+)*$

Description (click to enlarge)

说明(点击放大)

Regular expression visualization

正则表达式可视化

Demo

演示

http://jsfiddle.net/r2LsN/

http://jsfiddle.net/r2LsN/

Discussion

讨论

The regex defines all the allowed patterns firstly:

正则表达式首先定义了所有允许的模式:

  1. Tags with body: <tag>...</tag>
  2. Tags without body: <tag/>(here we can find zero or more spaced before /)
  3. Comments <!-- ... -->
  4. Any text that is not <or >.
  1. 带有身体的标签: <tag>...</tag>
  2. 没有正文的标签:(<tag/>在这里我们可以找到零个或多个间隔/
  3. 评论 <!-- ... -->
  4. 任何不是<或 的文本>

then these patterns can appear zero or more times between the beginning and the end of the tested string: ^(?:pattern1|pattern2|pattern3|pattern4)*$.

然后这些模式可以出现开头和测试串的端部之间零次或多次:^(?:pattern1|pattern2|pattern3|pattern4)*$