[英]using regex to get the variable value of html tags
我試圖在 html 的某些文本之間獲取一個值,到目前為止沒有成功,我不能使用 html 敏捷包,因為它給出的數據僅存在於 html 標簽之間
public static string[] split_comments(string html)
{
html = html.ToLower();
html = html.Replace(@""""," ");
html 中的實際行是這樣的
// <meta itemprop="rating" content="4.7"> the 4.7 value changes every time and I need to get this value
Match match = Regex.Match(html, @"<meta itemprop=rating content=([A-Za-z0-9\-]+)\>$");
if (match.Success)
{
// Finally, we get the Group value and display it.
string key = match.Groups[1].Value;
}
所以我試圖獲得 html 的標簽,並且在該標簽中我希望獲得始終可變的數據。
string html = "<meta itemprop=\"rating\" content=\"4.7\">";
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(html);
var content = doc.DocumentNode
.Element("meta")
.Attributes["content"].Value;
- 編輯 -
從你第一次接受然后不接受答案,我猜你拿了代碼並用你真正的 html 運行並看到它返回了錯誤的結果。
這並不表明答案不正確,因為它可以與您發布的代碼段一起正常工作。
因此,通過大膽猜測並假設您的真實 html 中還有其他具有itemprop
屬性的meta
標記,例如
<meta itemprop="rating" content="4.7">
<meta itemprop="somekey" content="somevalue">
代碼將是:
var content = doc.DocumentNode
.Descendants("meta")
.Where(n => n.Attributes["itemprop"] != null && n.Attributes["itemprop"].Value == "rating")
.Select(n => n.Attributes["content"].Value)
.First();
首先你應該替換它:
html = html.Replace(@""""," ");
接着就,隨即:
html = html.Replace(@"""","");
並更改您的正則表達式:
Match match = Regex.Match(html, @"<meta itemprop=rating content=([A-Za-z0-9\-.]+)\>$");
否則你的 if 將永遠是錯誤的。 之后你可以簡單地使用 substring:
html = html.Substring(html.IndexOf("content=") + 8);
html = html.Substring(0, html.Length - 1);
我希望這會有所幫助
這里
html = html.Replace(@""""," ");
你用空格替換雙引號。 因此,您的示例字符串現在如下所示:
<meta itemprop= rating content= 4.7 >
但是,您的正則表達式匹配沒有這些額外空格的文本。 此外,您的正則表達式在結束>
之前需要一個反斜杠,這在示例中不存在。
您的正則表達式應該類似於@"\<meta.+?content\=\"(.+)\"\>"
。 雖然用正則表達式解析 HTLM 是一件壞事。
試試這個:
double searchedValue;
Regex reg = new Regex(@"content= (?<groupname>.*?) >");
var matches = reg.Match(@"<meta itemprop= rating content= 4.7 >");
var value = matches.Groups["groupname"].Value;
//maybe you need to replace like value.Replace('.',',')
double.TryParse(value , out searchedValue);
(?<groupname>... )
建立一個組。 您可以使用matches.Groups["groupname"].Value
訪問該值
.*?
正在閱讀“ >
”的下一場比賽。
如果您不使用“ ?
”,它將在您的文本中搜索“ >
”的最后一個匹配項。
祝你好運 =)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.