本帖最后由 遗憾迟香 于 2020-4-27 20:32 编辑
第一次练习C#的正则表达式AAA云推荐码的格式为:
AAAYUN{0}-{1}
{0}为13个字符,{1}为八位日期
正则表达式如下
AAAYUN.{13}-\d{8}
源码:
[C#] 纯文本查看 复制代码 /// <summary>
/// 匹配推荐码
/// </summary>
/// <param name="s">获取到的网页源码</param>
private static void GetCode(string s)
{
Regex rg = new Regex(@"AAAYUN.{13}-\d{8}", RegexOptions.Multiline | RegexOptions.Singleline);
MatchCollection matches = rg.Matches(s);
DateTime dt = DateTime.Now;
foreach (Match item in matches)
{
string value = item.Value;
DateTime time = DateTime.ParseExact(value.Substring(20, 8), "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture);
if (time > dt)//排除已过期的推荐码
Console.WriteLine(value);
}
}
/// <summary>
/// Get请求
/// </summary>
/// <param name="url">Url</param>
/// <returns></returns>
private static string Get(string url)
{
string message = string.Empty;
HttpWebRequest request;
try
{
request = (HttpWebRequest)WebRequest.Create(url);
request.Accept = "text/html, application/xhtml+xml, */*";
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)";
request.KeepAlive = true;
request.ProtocolVersion = HttpVersion.Version11;
request.Timeout = 20000;
ServicePointManager.Expect100Continue = false;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
message = reader.ReadToEnd();
reader.Close();
responseStream.Close();
}
catch (Exception err)
{
message = err.Message;
}
return message;
} |