c# - 使用正则表达式从站点抓取链接时出错
问题描述
我正在尝试使用正则表达式从某些文本中获取匹配项,但代码无法产生任何结果。
文本包含
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.'
有解决办法吗?
解决方案
你可能会得到你的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
值。
推荐阅读
- javascript - 正则表达式接受特殊字符时出错
- vb.net - 在 Visual Basic 中列出没有文件路径的 ListBox 中的文件
- c# - 如何使 MediaElement 在 C# wpf .NET Framework MVVM 内工作
- java - java.sql.SQLFeatureNotSupportedException:方法 org.postgresql.jdbc.PgResultSet.getNString(int) 尚未实现
- wso2 - 如何在 WSO2 中为端口 9711 禁用 TLS 1.0、TLS 1.1
- math - 我们如何识别一组近似矩形的像素?
- regex - 正则表达式忽略最后一个空格
- blazor - 在 Blazor WebAssembly 中将程序集添加到客户端的浏览器
- reporting-services - SSRS 2019 - 如何重复包含嵌套矩阵的表的标题行?
- php - 此请求没有可用的响应数据