2017-02-17 77 views
-1

我收到了「格式不正確」的錨定標記(要麼沒有關閉,沒有文本或自閉合標記)通過飼料我無法控制,需要糾正它們 - 這裏是三個例子:「格式不正確」的錨定標記正則表達式

  • <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; 
    }