正则匹配的例子

最近开发接口需要从文档里面复制接口信息,一看好多参数,瞬间就不想下手了,想了下,用正则匹配岂不是正好。

先来一个HttpWebRequest帮助方法,很简单。

1   public string GetHtmlString(string url)
2         {
3             HttpWebRequest httpRq = WebRequest.Create(url) as HttpWebRequest;
4             HttpWebResponse response = httpRq.GetResponse() as HttpWebResponse;
5             Stream str = response.GetResponseStream();
6             StreamReader sr = new StreamReader(str, Encoding.UTF8);
7             string html = sr.ReadToEnd();
8             return html;
9         }
View Code

然后就开始根据Google浏览器的F12查找我要的元素了~~~

然后就开始正则匹配,上代码:

 1  public string GetBigTitle() {
 2             string bigTitle = "";
 3             StringBuilder sb = new StringBuilder();
 4             Common.HttpHelper ch = new Common.HttpHelper();
 5             string outHtml = ch.GetHtmlString(txt_url.Text);
 6             string reg = "<strong class="ph b">(.*?)</strong>";//正则表达
 7             MatchCollection Matchs = Regex.Matches(outHtml, reg, RegexOptions.Singleline | RegexOptions.IgnoreCase);//开始匹配
 8             for (int i = 0; i < Matchs.Count; i++)
 9             {
10                 sb.Append("this."+ Matchs[i].Groups[1].Value.Substring(1)+"="+ Matchs[i].Groups[1].Value.Substring(1).ToLower()+"<br/>");
11                 bigTitle += Matchs[i].Groups[1].Value.Substring(1).ToLower() +",";
12             }
13             return bigTitle+"<br/>"+sb.ToString();
14         }
View Code

这里稍微说下 MatchCollection 类表示成功的非重叠匹配的只读的集合,MatchCollection 的实例是由 Regex.Matches 属性返回的,通过在字符串中找到所有与Regex中指定的匹配并填充 MatchCollection。

                  GroupCollection 类表示被捕获的组的集合,并在单个匹配项中返回该捕获组的集合。GroupCollection 的实例在 Match.Groups 属性返回的集合中返回。最终我们从Groups中取我们想要的值。

最后,看看我们的额结果图:

虽然有点粗糙,却简单实用,大功告成。

原文地址:https://www.cnblogs.com/ypyhy/p/6019703.html