代码之家  ›  专栏  ›  技术社区  ›  Sailing Judo

如何修复此正则表达式以允许特定字符串?

  •  0
  • Sailing Judo  · 技术社区  · 14 年前

    此regex来自atwood,用于筛选除ref和a title之外的锚标记:

     <a\shref="(\#\d+|(https?|ftp)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+)"(\stitle="[^"]+")?\s?>
    

    我需要允许特定匹配的额外属性:target=“\u blank”。因此,应允许以下URL:

     <a href="http://www.google.com" target="_blank">
    

    我试着把模式改成:

     <a\shref="(\#\d+|(https?|ftp)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+)"(\stitle="[^"]+")(\starget="_blank")?\s?>
     <a\shref="(\#\d+|(https?|ftp)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+)"(\stitle="[^"]+")(\starget=\"_blank\")?\s?>
    

    显然我对regex不太了解。如何调整模式以允许空白目标和其他目标?

    2 回复  |  直到 14 年前
        1
  •  1
  •   Jason    14 年前
    <a\shref="(\#\d+|(https?|ftp)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+)"\s(target=\"_blank\")>
    

    会照你说的做。

    如果你是一个regex nub,让我推荐regexbuddy。它是一个程序,允许您在示例文本或示例文件上测试正则表达式。

    节省了很多时间。

    http://www.regular-expressions.info/regexbuddy.html (Regex好友)

    http://www.regular-expressions.info 也是很好的资源

        2
  •  1
  •   zellio    14 年前
    <a\shref="(\#\d+|(https?|ftp)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+)"(\stitle="[^"]+")(\starget="_blank")>