2009-06-08 10 views
1

アンカータグの内側からhttpリンクを抽出しますか?抽出する拡張子は、WMVファイルのみである必要があります。アンカータグからURLを抽出するための正規表現

+0

あなたはあなたの試合の例を持っていますか? –

+0

私は次のように一致するようにしようとしています: http://www.highoncoding.com/videos/ListBoxSelection.wmv おかげで、私は私ができる希望 – azamsharp

答えて

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パーザがこのタイプの問題の正規表現よりも優れている理由を理解しているといいでしょう。

+0

listbox selection video 私は私を与える必要があり、正規表現を必要としますupvoteこれ以上の回:) –

関連する問題