2009-06-08 61 views

回答

1

正則表達式:

<a\\s*href\\s*=\\s*(?:(\"|\')(?<link>[^\"]*.wmv)(\"|\'))\\s*>(?<name>.*)\\s*</a> 

[注意:\ S *是在幾個地方用來匹配可能出現在HTML額外的空格字符]

樣品C#代碼:

/// <summary> 
/// Assigns proper values to link and name, if the htmlId matches the pattern 
/// Matches only for .wmv files 
/// </summary> 
/// <returns>true if success, false otherwise</returns> 
public static bool TryGetHrefDetailsWMV(string htmlATag, out string wmvLink, out string name) 
{ 
    wmvLink = null; 
    name = null; 

    string pattern = "<a\\s*href\\s*=\\s*(?:(\"|\')(?<link>[^\"]*.wmv)(\"|\'))\\s*>(?<name>.*)\\s*</a>"; 

    if (Regex.IsMatch(htmlATag, pattern)) 
    { 
     Regex r = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Compiled); 
     wmvLink = r.Match(htmlATag).Result("${link}"); 
     name = r.Match(htmlATag).Result("${name}"); 
     return true; 
    } 
    else 
     return false; 
} 

MyRegEx.TryGetHrefDetailsWMV("<td><a href='/path/to/file'>Name of File</a></td>", 
       out wmvLink, out name); // No match 
MyRegEx.TryGetHrefDetailsWMV("<td><a href='/path/to/file.wmv'>Name of File</a></td>", 
       out wmvLink, out name); // Match 
MyRegEx.TryGetHrefDetailsWMV("<td><a href='/path/to/file.wmv' >Name of File</a></td>", out wmvLink, out name); // Match 
2

因爲HTML的語法規則是如此寬鬆,這是相當困難與任何可靠性做(除非,說,你知道絕對肯定的是,所有的標籤將使用它們的屬性值周圍雙引號)。下面是爲宗旨一些相當一般的基於正則表達式代碼:

function extract_urls($html) { 
    $html = preg_replace('<!--.*?-->', '', $html); 
    preg_match_all('/<a\s+[^>]*href="([^"]+)"[^>]*>/is', $html, $matches); 
    foreach($matches[1] as $url) { 
     $url = str_replace('&amp;', '&', trim($url)); 
     if(preg_match('/\.wmv\b/i', $url) && !in_array($url, $urls)) 
      $urls[] = $url; 
    } 
    preg_match_all('/<a\s+[^>]*href=\'([^\']+)\'[^>]*>/is', $html, $matches); 
    foreach($matches[1] as $url) { 
     $url = str_replace('&amp;', '&', trim($url)); 
     if(preg_match('/\.wmv\b/i', $url) && !in_array($url, $urls)) 
      $urls[] = $url; 
    } 
    preg_match_all('/<a\s+[^>]*href=([^"\'][^> ]*)[^>]*>/is', $html, $matches); 
    foreach($matches[1] as $url) { 
     $url = str_replace('&amp;', '&', trim($url)); 
     if(preg_match('/\.wmv\b/i', $url) && !in_array($url, $urls)) 
      $urls[] = $url; 
    } 
    return $urls; 
} 
1

我不會用正則表達式做到這一點 - 我可能會使用jQuery:

jQuery('a[href$=.wmv]').attr('href') 

這種比較混亂的簡化正則表達式的例子,其(如說明)不應對挑剔/複雜的標記,你會希望瞭解爲什麼DOM解析器是不是這種類型的問題,一個正則表達式更好。