我試圖使用正則表達(dá)式從某些文本中獲取匹配項(xiàng),但代碼無(wú)法產(chǎn)生任何結(jié)果。正文包含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);我在數(shù)組中收到錯(cuò)誤:System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'有解決辦法嗎?
1 回答

慕無(wú)忌1623718
TA貢獻(xiàn)1744條經(jīng)驗(yàn) 獲得超4個(gè)贊
您可能會(huì)array
使用
var array = Regex.Matches(text, "\"https://www\\.localhost\\.com/en/account\\?dwcont=([^\"]+)") .Cast<Match>() .Select(x => x.Groups[1].Value);
然后,使用獲取第一個(gè)匹配項(xiàng)
text2 = array.FirstOrDefault();
請(qǐng)注意,您需要在正則表達(dá)式模式中轉(zhuǎn)義文字.
和符號(hào),并且由于您使用的是常規(guī)字符串文字,因此您應(yīng)該使用雙反斜杠來(lái)創(chuàng)建正則表達(dá)式轉(zhuǎn)義。?
您收到Index was outside the bounds of the array
錯(cuò)誤是因?yàn)槟恼齽t表達(dá)式無(wú)法提取任何匹配項(xiàng)并array[0]
嘗試訪問(wèn)null
值。
- 1 回答
- 0 關(guān)注
- 123 瀏覽
添加回答
舉報(bào)
0/150
提交
取消