2017-02-17 5 views
-1

フィードを介して「不正な形式の」アンカータグ(閉じられていないか、テキストがないか、自己終了しているタグ)を受け取ったため、修正できません。 3例:「不正な形式の」アンカータグRegex

  • <a class="some-class" href="www.something.com/Resource.PDF" target="_blank">(なし終了タグ/ない自動閉鎖)
  • <a class="some-class" href="www.something.com/Resource.PDF" target="_blank"></a>(テキストなし)
  • <a class="some-class" href="www.something.com/Resource.PDF" target="_blank"/>(自動閉鎖)

私が探していますC#の正規表現/正規表現のセット.HTML文字列に上記の出現箇所があります。

これまでのところ、私は次のようしている:

  • (?<anchor><a\s.+?\/{0}>)(?<text>(.*?){0})(<\/a>) ---私の目標は、これらを交換することで自動閉鎖アンカーに

を検索----テキスト

  • (?<anchor><a\s.+?\/>)せずにアンカーを検索リソースをテキストとして含む出現: <a class="some-class" href="www.something.com/Resource.PDF" target="_blank">Resource.PDF</a>

    助けが大いにありがとうテッド。

  • 答えて

    0

    おそらくこれを行うには良い方法がありますが、誰かが同様の問題を抱えている場合は、すべてのアンカータグを見つけて、不正なタグを探すのではなく、必要に応じて修正することで解決しました。 (https://regex101.com/r/xMnfY8/1): (?<anchor><a\s.*?href=[""'](?<anchorUrl>.+?)[""'].*?>)(?<anchorText>[\s\w]*)(?<anchorClose><\/a>|<|$|\b)

    それからタグを固定するの世話をするためにC#コードを使用する:

    public string FixAnchorTags(string html) 
        { 
         var result = html; 
         var indexAdjustment = 0; 
    
         foreach (Match match in _anchorTagRegex.Matches(html)) 
         { 
          var anchor = match.Groups["anchor"]; 
          var anchorUrl = match.Groups["anchorUrl"]; 
          var anchorText = match.Groups["anchorText"]; 
          var anchorClose = match.Groups["anchorClose"];     
    
          if (anchor.Value.EndsWith("/>")) 
          {      
           result = result.Remove(anchor.Index + indexAdjustment, anchor.Length).Insert(anchor.Index + indexAdjustment, anchor.Value.Replace("/>", ">")); 
           indexAdjustment -= 1; 
          } 
    
          if (string.IsNullOrWhiteSpace(anchorText.Value)) 
          { 
           var fileName = Path.GetFileNameWithoutExtension(anchorUrl.Value); 
           result = result.Insert(anchorText.Index + indexAdjustment, fileName); 
           indexAdjustment += fileName.Length; 
          } 
    
          if (!anchorClose.Value.Matches("</a>")) 
          { 
           result = result.Insert(anchorClose.Index + indexAdjustment, "</a>"); 
           indexAdjustment += 4; 
          } 
         } 
    
         return result; 
        } 
    
    関連する問題