c#regex输出字符串不符合我的预期
本文关键字:我的 不符合 输出 字符串 c#regex | 更新日期: 2023-09-27 18:00:20
我使用以下代码通过扫描任何产品页面的html源从amazon.com检索运费。但是输出不是我想要的。下面是代码。
regexString = "<span class='"plusShippingText'">(.*)</span>";
match = Regex.Match(htmlSource, regexString);
string shipCost = match.Groups[1].Value;
MessageBox.Show(shipCost);
它显示了一个消息框,将退货运费显示为
+ Free Shipping</span>
但事实上,我只需要以下干净的文本。
Free Shipping
请帮我解决这个问题。
您可以尝试以下代码吗(尽管使用regex进行HTML解析是个坏主意):
string shipCostHtml = Regex.Match(htmlSource, "(?<=<span class='"plusShippingText'">).*?(?=</span>)").Value;
string shipCost = System.Net.WebUtility.HtmlDecode(shipCostHtml);
shipCost = shipCost.Trim(' ', '+', ''xa0');
您的正则表达式几乎可以,您只需要将贪婪的(.*)
替换为懒惰的(.*?)
。
使用CCD_ 3是如何解决的。
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(htmlSource);
string shipCostHtml = doc.DocumentNode.SelectSingleNode("//span[@class='plusShippingText']").InnerText;
string shipCost = System.Net.WebUtility.HtmlDecode(shipCostHtml);
shipCost = shipCost.Trim(' ', '+', ''xa0');
现在,当亚马逊决定向<span>
添加一些附加属性时,您可以免受这种情况的影响,例如:<span class='plusShippingText newClass'>
或<span style='{color:blue}' class='plusShippingText'>
等。
您需要删除HTML标记您可以使用以下功能:
shipCost = System.Net.WebUtility.HtmlDecode(shipCost).Replace("+","").Trim()