Regular Expression to match open and closed html tags

This question already has an answer here:

  • RegEx match open tags except XHTML self-contained tags 35 answers

  • 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:

  • Tags with body: <tag>...</tag>
  • Tags without body: <tag/> (here we can find zero or more spaced before / )
  • Comments <!-- ... -->
  • Any text that is not < or > .
  • then these patterns can appear zero or more times between the beginning and the end of the tested string: ^(?:pattern1|pattern2|pattern3|pattern4)*$ .

    链接地址: http://www.djcxy.com/p/76864.html

    上一篇: 正则表达式将输入标签拉出窗体

    下一篇: 正则表达式匹配打开和关闭的html标签