Regular Expression to match open and closed html tags
This question already has an answer here:
The test method returns true for match2 because it has found a match .
In order to fix it, change your regex this way:
^(?:<(w+)(?:(?:s+w+(?:s*=s*(?:".*?"|'.*?'|[^'">s]+))?)+s*|s*)>[^<>]*</1+s*>|<w+(?:(?:s+w+(?:s*=s*(?:".*?"|'.*?'|[^'">s]+))?)+s*|s*)/>|<!--.*?-->|[^<>]+)*$
Description (click to enlarge)
Demo
http://jsfiddle.net/r2LsN/
Discussion
The regex defines all the allowed patterns firstly:
<tag>...</tag> <tag/> (here we can find zero or more spaced before / ) <!-- ... --> < or > . then these patterns can appear zero or more times between the beginning and the end of the tested string: ^(?:pattern1|pattern2|pattern3|pattern4)*$ .
上一篇: 正则表达式将输入标签拉出窗体
下一篇: 正则表达式匹配打开和关闭的html标签
