使用正则表达式获取指定类名以外的所有链接

时间:2012-06-26 11:20:25

标签: php javascript asp.net regex

我想从HTML文档中获取所有链接,除了具有指定类名的链接,使用REGEX。

例如:

<a href="someSite" class="className">qwe</a> <a href="someSite">qwe</a>

因此,我希望链接中只有 href =“someSite”,而不包含等于“className”的类

我创建了正则表达式:

(?<=<\s*a.*)href\s*?=\s*?("|').*?("|')

返回exacly我想要的,但来自所有链接,我不知道如何向我的Regex添加一个异常,以便不重新启动指定类名的链接

任何帮助将不胜感激:)

5 个答案:

答案 0 :(得分:2)

如果您愿意使用jQuery,则可以在不使用Regex的情况下执行此操作:

 var list = $("a", document).filter(function () {
                return $(this).hasClass("className") == false;
            });

答案 1 :(得分:0)

假设你在某个变量中有HTML,你可以使用http://code.google.com/p/phpquery/wiki/Selectors(phpquery - php的php jQuery-esq)。

答案 2 :(得分:0)

其他答案是明智的。但如果出于任何原因你坚持使用REGEX方法。试试这个。

我假设您正在通过PHP(或.NET)进行REGEX,因为您的模式包含一个负面的后置断言,这在JavaScript中不受支持。

我还将匹配与过滤掉那些带有错误类的匹配,因为REGEX对后者来说并不理想(因为class属性可能出现在链接开始标记内的任何一点)。

$str = "<a href='bad_href' class='badClass'>bad link</a> <a href='good_href'>good link</a>";
preg_match_all('/<a.+(href ?= ?("|\')[^\2]*\2).*>.*<\/a>/U', $str, $matches);
foreach($matches[0] as $key => $match)
    if (preg_match('/class=(\'|")[^\1]*badClass[^\1]*\1/', $match))
        unset($matches[1][$key]);
$matches = $matches[1]; //array containing "href='good_href'"

答案 3 :(得分:0)

var aList= document.getElementsByTagName('a');
for (var i in aList) {
   if (aList.hasOwnProperty(i)) {
     if (aList[i].className.indexOf(YourClassName) != -1) continue;
    //... 
    //... Your code
   }
}

答案 4 :(得分:0)

声明:

正如其他人已经或已经指出的那样,使用正则表达式解析非常规语言充满了危险!最好使用专门为该作业设计的专用解析器,尤其是在解析HTML标签汤时。

那说......

如果您坚持使用正则表达式,那么这是一个经过测试的PHP脚本,它实现了一个“非常好”的正则表达式解决方案:

<?php // test.php Rev:20120626_2100

function strip_html_anchor_tags_not_having_class($text) {
    $re_html_anchor_not_having_class ='% # Rev:20120626_1300
    # Match an HTML 4.01 A element NOT having a specific class.
    <a\b                   # Anchor element start tag open delimiter
    (?:                    # Zero or more attributes before CLASS.
      \s+                  # Attributes are separated by whitespace.
      (?!class\b)          # Only non-CLASS attributes here.
      [A-Za-z][\w\-:.]*    # Attribute name is required.
      (?:                  # Attribute value is optional.
        \s*=\s*            # Name and value separated by =
        (?:                # Group for value alternatives.
          "[^"]*"          # Either a double-quoted string,
        | \'[^\']*\'       # or a single-quoted string,
        | [\w\-:.]+        # or a non-quoted string.
        )                  # End group of value alternatives.
      )?                   # Attribute value is optional.
    )*                     # Zero or more attributes before CLASS.
    (?:                    # Optional CLASS (but only if NOT MyClass).
      \s+                  # CLASS attribute is separated by whitespace.
      class                # (case insensitive) CLASS attribute name.
      \s*=\s*              # Name and value separated by =
      (?:                  # Group allowable CLASS value alternatives.
        (?-i)              # Use case-sensitive match for CLASS value.
        "                  # Either a double-quoted value...
        (?:                # Single-char-step through CLASS value.
          (?!              # Assert each position is NOT MyClass.
            (?<=["\s])     # Preceded by opening quote or space.
            MyClass        # (case sensitive) CLASS value to NOT be matched.
            (?=["\s])      # Followed by closing quote or space.
          )                # End assert each position is NOT MyClass.
          [^"]             # Safe to match next CLASS value char.
        )*                 # Single-char-step through CLASS value.
        "                  # Ok. DQ value does not contain MyClass.
      | \'                 # Or a single-quoted value...
        (?:                # Single-char-step through CLASS value.
          (?!              # Assert each position is NOT MyClass.
            (?<=[\'\s])    # Preceded by opening quote or space.
            MyClass        # (case sensitive) CLASS value to NOT be matched.
            (?=[\'\s])     # Followed by closing quote or space.
          )                # End assert each position is NOT MyClass.
          [^\']            # Safe to match next CLASS value char.
        )*                 # Single-char-step through CLASS value.
        \'                 # Ok. SQ value does not contain MyClass.
      |                    # Or a non-quoted, non-MyClass value...
        (?!                # Assert this value is NOT MyClass.
          MyClass          # (case sensitive) CLASS value to NOT be matched.
        )                  # Ok. NQ value is not MyClass.
        [\w\-:.]+          # Safe to match non-quoted CLASS value.
      )                    # End group of allowable CLASS values.
      (?:                  # Zero or more attribs allowed after CLASS.
        \s+                # Attributes are separated by whitespace.
        [A-Za-z][\w\-:.]*  # Attribute name is required.
        (?:                # Attribute value is optional.
          \s*=\s*          # Name and value separated by =
          (?:              # Group for value alternatives.
            "[^"]*"        # Either a double-quoted string,
          | \'[^\']*\'     # or a single-quoted string,
          | [\w\-:.]+      # or a non-quoted string.
          )                # End group of value alternatives.
        )?                 # Attribute value is optional.
      )*                   # Zero or more attributes after CLASS.
    )?                     # Optional CLASS (but only if NOT MyClass).
    \s*                    # Optional whitespace before closing >
    >                      # Anchor element start tag close delimiter
    (                      # $1: Anchor element contents.
      [^<]*                # {normal*} Zero or more non-<
      (?:                  # Begin {(special normal*)*} construct
        <                  # {special} Allow a < but only if
        (?!/?a\b)          # not the start of the </a> close tag.
        [^<]*              # more {normal*} Zero or more non-<
      )*                   # Finish {(special normal*)*} construct
    )                      # End $1: Anchor element contents.
    </a\s*>                # A element close tag.
    %ix';
    // Remove all matching start and end tags but keep the element contents.
    return preg_replace($re_html_anchor_not_having_class, '$1', $text);
}
$input = file_get_contents('testdata.html');
$output = strip_html_anchor_tags_not_having_class($input);
file_put_contents('testdata_out.html', $output);
?>

function strip_html_anchor_tags_not_having_class($text)

此函数剥离所有HTML 4.01 Anchor元素(即<A>标记)的开始和匹配结束标记,这些元素不具有包含以下内容的特定(区分大小写)CLASS属性值:{{ 1}}。 MyClass值可以包含任意数量的值,但其中一个值必须完全为:CLASS。 Anchor标记名称和CLASS属性名称不区分大小写匹配。

示例输入(MyClass):

testdata.html

示例输出(<h2>Paragraph contains links to be preserved (CLASS has "MyClass"):</h2> <p> Single DQ matching CLASS: <a href="URL" class="MyClass">Test 01</a>. Single SQ matching CLASS: <a href="URL" class='MyClass'>Test 02</a>. Single NQ matching CLASS: <a href="URL" class=MyClass>Test 03</a>. Variable whitespace: <a href = "URL" class = MyClass >Test 04</a>. Variable capitalization: <A HREF = "URL" CLASS = "MyClass" >Test 04</A>. Reversed attribute order: <a class="MyClass" href="URL">Test 05</a> Class before MyClass: <a href="URL" class="Pre MyClass">Test 06</a>. Class after MyClass: <a href="URL" class="MyClass Post">Test 07</a>. Sandwiched MyClass: <a href="URL" class="Pre MyClass Post">Test 08</a>. Link with HTML content: <a class="MyClass" href="URL"><b>Test</b> 09</a>. </p> <h2>Paragraph contains links to be stripped (NO CLASS with "MyClass"):</h2> <p> Case does not match: <a href="URL" class="myclass">TEST 10</a>. CLASS not whole word: <a href="URL" class="NotMyClass">TEST 11</a>. No class attribute: <a href="URL">TEST 12</a>. Link with HTML content: <a class="NotMyClass" href="URL"><b>Test</b> 13</a>. </p> ):

testdata_out.html

希望提升正则表达式的读者可以很好地研究这个(相当长而复杂)的正则表达式。它精确地手工制作,既准确又快速,并实现了几种先进的效率技术。当然,它完全被评论为仅仅是人类的可读性。这个例子清楚地表明“常规表达式”已演变成一种丰富的(非 REGULAR )编程语言。

请注意,此解决方案将始终存在边缘情况。例如CDATA部分,注释,脚本,样式和标记属性值中的邪恶字符串可能会使其失效。 (参见上面的免责声明。)也就是说,这个解决方案在许多情况下都会做得很好(但永远不会 100%可靠!)