Skip to main content
 首页 » 编程设计

如果满足条件,C# 用另一个正则表达式选择替换正则表达式选择

2024年05月22日42powertoolsteam

我正在解析一些 html 代码,我正在尝试的是当且仅当 alt 为空时,用它的 src 值(没有后缀)替换 img 中的 alt。

例子:

输入:

... some HTML here .... 
<img src="my_image.jpg" alt="something_is_already_here" width="450" height="300"> 
... some HTML here .... 
<img src="my_image2.jpg" alt="" width="450" height="300" 

输出:

... some HTML here .... 
<img src="my_image.jpg" alt="something_is_already_here" width="450" height="300"> 
... some HTML here .... 
<img src="my_image2.jpg" alt="my_image2" width="450" height="300"> 

我已经为 src 和 alt 编写了正则表达式,但不知道如何使用它来完成我真正需要的事情。

//src=\"([^"]*)\.jpg\" 
string srcPattern = "src=\\\"([^\"]*)\\.jpg\\\""; 
//alt=\"([^"]*)\" 
string altPattern = "alt=\\\"([^\"]*)\\\""; 
Regex rSrc = new Regex(srcPattern); 
Regex rAlt = new Regex(altPattern); 

请您参考如下方法:

这是使用 HTML 解析器(HtmlAgilityPack - 作为 NuGet 包安装)的方法:您可以将 URL 或 HTML 字符串传递给 HtmlAgilityPackPopulateAltWithSrcIfEmpty方法,输出将是在 img 标签中填充了 alts 的 HTML 字符串。

使用的 XPath //img[string-length(@alt) = 0]选择所有 img标签 ( //img ) 其 alt属性值为空 ( [string-length(@alt) = 0] )。

alt仅填充了 src 的一部分如果src值以 .jpg 结尾扩大。然后,只有扩展名之前的部分用于设置alt。属性。

public string HtmlAgilityPackPopulateAltWithSrcIfEmpty(string html) 
    { 
        HtmlAgilityPack.HtmlDocument hap; 
        Uri uriResult; 
        if (Uri.TryCreate(html, UriKind.Absolute, out uriResult) && uriResult.Scheme == Uri.UriSchemeHttp) 
        { // html is a URL  
            var doc = new HtmlAgilityPack.HtmlWeb(); 
            hap = doc.Load(uriResult.AbsoluteUri); 
        } 
        else 
        { // html is a string 
            hap = new HtmlAgilityPack.HtmlDocument(); 
            hap.LoadHtml(html); 
        } 
        var nodes = hap.DocumentNode.SelectNodes("//img[string-length(@alt) = 0]"); 
        if (nodes != null) 
        { 
            foreach (var node in nodes) 
            { 
                var val = node.GetAttributeValue("src", string.Empty); 
                if (val.ToUpper().EndsWith(".JPG")) 
                    node.SetAttributeValue("alt", val.Substring(0, val.Length - 4)); 
            } 
        } 
        var ffg = hap.DocumentNode.OuterHtml; 
        return hap.DocumentNode.OuterHtml; 
    } 

像这样使用它:

var s = "<img src=\"my_image.jpg\" alt=\"something_is_already_here\" width=\"450\" height=\"300\"><img src=\"my_image2.jpg\" alt=\"\" width=\"450\" height=\"300\">"; 
var new_html = HtmlAgilityPackPopulateAltWithSrcIfEmpty(s); 

结果:

<img src="my_image.jpg" alt="something_is_already_here" width="450" height="300"><img src="my_image2.jpg" alt="my_image2" width="450" height="300">