首页 > 解决方案 > 使用正则表达式从站点抓取链接时出错

问题描述

我正在尝试使用正则表达式从某些文本中获取匹配项,但代码无法产生任何结果。

文本包含

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.'

有解决办法吗?

标签: c#regex

解决方案


你可能会得到你的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值。


推荐阅读