简体   繁体   English

JavaScript正则表达式,匹配P但不匹配PARAM

[英]JavaScript Regex, match P but not PARAM

Using JavaScript RegEx. 使用JavaScript RegEx。

How can I match a <p> element(including attributes), but not <param> or other HTML elements starting with a "P". 如何匹配<p>元素(包括属性),而不匹配<param>或其他以“ P”开头的HTML元素。

Try: 尝试:

/(<p(?:\s+[^>]*)?>)/i

/
 (        #start capture group
  <p       #match '<p'
  (?:      #start non-capture group
    \s+     #match one or more white space characters
    [^>]*   #match zero or more characters that arent >
  )?       #end non-capture group - make it optional
  >        #match '>'
 )        #end capture group
/i        #end regexp - make case insensitive
/<p\b[^>]*>/i

\\b matches a word boundary; \\b匹配单词边界; coming after the 'p' it means the next character (if there is a next character) is not a letter, digit or underscore. 在“ p”之后,表示下一个字符(如果有下一个字符)不是字母,数字或下划线。

Disclosure: [^>]* isn't really the correct way to match the rest of the tag, since attribute values can legally contain angle brackets. 披露: [^>]*并不是匹配其余标签的正确方法,因为属性值可以合法地包含尖括号。 But it's probably good enough, and that's not what the question is about anyway. 但这可能已经足够好了,无论如何这不是问题所在。

<(p|P)([\\s].*)?>

seems to work good =). 似乎效果不错=)。 But you shouldn't use RegEx when you can use DOM, or even XML/XPath/whatever. 但是,当您可以使用DOM甚至XML / XPath /任何东西时,都不应该使用RegEx。

这是我的尝试:

/\<P(\s+\w+=\"?[^\"\s\>]*\"?)*\>/gi
/<(?:p|P)\s+/.exec(s);

尽管它与整个标签不匹配,但是考虑到属性中允许使用标签结束符号>,这相当复杂。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM