亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用正則表達式從網站抓取鏈接時出錯

使用正則表達式從網站抓取鏈接時出錯

C#
一只名叫tom的貓 2023-09-24 10:54:52
我試圖使用正則表達式從某些文本中獲取匹配項,但代碼無法產生任何結果。正文包含action="https://www.localhost.com/en/account?dwcont=C338711466"我的代碼是HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("https://www.localhost.com/en/account");httpWebRequest.Method = "GET";httpWebRequest.CookieContainer = this.cookieJar;string text2;using (StreamReader streamReader = new StreamReader(httpWebRequest.GetResponse().GetResponseStream())){   string text = streamReader.ReadToEnd().Trim().ToString();   string[] array = (from Match match in Regex.Matches(text, "\"https://www.localhost.com/en/account?dwcont=(.+?)\"")                     select match.Groups[1].Value).ToArray<string>();   text2 = array[0];}MessageBox.Show(text2);我在數組中收到錯誤:System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'有解決辦法嗎?
查看完整描述

1 回答

?
慕無忌1623718

TA貢獻1744條經驗 獲得超4個贊

您可能會array使用

var array = Regex.Matches(text, "\"https://www\\.localhost\\.com/en/account\\?dwcont=([^\"]+)")
    .Cast<Match>()
    .Select(x => x.Groups[1].Value);

然后,使用獲取第一個匹配項

text2 = array.FirstOrDefault();

請注意,您需要在正則表達式模式中轉義文字.和符號,并且由于您使用的是常規字符串文字,因此您應該使用雙反斜杠來創建正則表達式轉義。?

您收到Index was outside the bounds of the array錯誤是因為您的正則表達式無法提取任何匹配項并array[0]嘗試訪問null值。


查看完整回答
反對 回復 2023-09-24
  • 1 回答
  • 0 關注
  • 125 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號