【问题标题】:Lookahead in JavaScript regexJavaScript 正则表达式中的前瞻
【发布时间】:2012-09-18 04:03:42
【问题描述】:

使用 JavaScript,我正在尝试替换 html 标记内的属性,并想出了这个正则表达式:

/<\s*tag[^>]*(attr)=['"]{1,1}([^'"\s]*)['"]{1,1}/ig;

这行得通。但是,我希望能够指定查找包含属性值的相同类型的引号。因此,例如,我想指定这是否是&lt;tag attr='data'&gt; 的形式,以便在第二个引号中查找单引号,而不是双引号。相反的情况,&lt;tag attr="data"&gt; 将是类似的;将 SECOND 标记与双引号匹配,而不是单引号。这是为了帮助我保护函数调用免受格式奇特的 HTML 的影响。

那么,我该如何实现呢?

谢谢!

【问题讨论】:

  • 使用 DOM 不是更有意义吗?

标签: regex lookahead


【解决方案1】:

试试这个:

/<tag[^>]*attr=(['"])(?:(?!\1)\S)*\1/ig;

说明:

<tag     # Match <tag (\s* is not needed since whitespace is illegal here)
[^>]*    # Match any non-> characters
attr=    # Match "attr="
(['"])   # Match a quote, remember which kind; {1,1} can be dropped (it's a no-op)
(?:      # Try to match
 (?!\1)  #  (unless it's the corresponding closing quote)
 \S      #  any non-whitespace character
)*       # any number of times
\1       # Match the corresponding closing quote

【讨论】:

  • 太棒了。感谢您的解释!真的让我变得更好,这样我就可以学习如何将其合并到其他正则表达式中。
【解决方案2】:

试试这个:

/<\s*tag[^>]*(attr)=(['"]{1,1})([^'"\s]*)\2{1,1}/ig;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多