如果我們要解析一個html,想要得到界面里的某個標簽值,那么用正則表達式比較方便。
比如,我們獲得了一個html界面,想獲得某個標簽的值(這個標簽有唯一屬性比如id=xxx,如果該類標簽沒有唯一屬性的話,那么將會得到該類標簽所有值),
代碼展示如下:
PRivate string GetValue(string data) { string returnStr = ""; MatchCollection mc = Regex.Matches(data, "<td id='cur_no2' .*?>.*?</td>"); //做一個要匹配的正則表達式, .*?表示所有的元素 foreach (Match m in mc) //遍歷匹配好的標簽 { string str = m.Value.Replace("</td>", ""); //去掉標簽后綴,用“”代替</td> str = Regex.Replace(str, "<.*?>", ""); // 去掉標簽前綴,用“”代替<.*?> returnStr += str; //如果匹配多個標簽,那么標簽里面的值拼接 } return returnStr; }
新聞熱點
疑難解答