正則表達式(基礎篇)

正則表達式的基本語法。


當然,和平常慣例一樣,正則表達式也有預定義字符集。有2種形式,用哪一種就是自己的偏好了,當然,2種混用也是可以的。




舉一個例子:有下面一段代碼。

@

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.IO;
namespace 網頁摳圖
{
    class Program
    {
        static void Main(string[] args)
        {
            WebClient wc = new WebClient();
            for (int i = 0; i < 9; i++)
            {
                string page = "";
                if (i > 0)
                {
                    page = "_" + i;
                }
                string html = wc.DownloadString("http://gb.cri.cn/42071/2015/03/25/7211s4912740" + page + ".htm");
                MatchCollection Matchs = Regex.Matches(html, "<IMG\\ssrc=\"(/mmsource/images/2015/03/25/[0-9]{2}/(\\w+.jpg))\">");
                string url = "http://gb.cri.cn";
                foreach (Match item in Matchs)
                {
                    if (item.Success)
                    {
                        //Console.WriteLine(item);
                        //Console.WriteLine(url+item.Groups[1].Value);
                        //Console.WriteLine(Path.Combine(@"E:\img",item.Groups[2].Value));
                        wc.DownloadFile(url + item.Groups[1].Value, Path.Combine(@"E:\img", item.Groups[2].Value));
                        Console.Write("*");
                    }
                }
            }
            Console.WriteLine("下載完成");
            Console.ReadKey();
        }
    }
}

@

如何用正則表達式準確的查找到上面這一段代碼呢?

1:查找全部代碼

@\n([[:space:][:alnum:][:punct:]]*)@

代碼中會出現字母,數字,特殊符號,空格,回車。我們便在‘’[]‘’裏用3個字符集進行選擇,並重復*次(即0或n次),首尾的@並不是表示開頭和結尾,只是表示代碼前後均有一個@符號,是一個爲了方便匹配自己設定的符號。當然還有更簡單的一種方式,就是將[:alnum:]和[:punct:]2者換成[:graph:],不管是特殊符號還是數字字母都是可打印字符。由此可見預定義字符類對於我們來查找一塊一塊的信息是十分便利的。

2:查找引入的系統命名空間(即using System.......)

^using.*\;$

開頭是using,結尾是分號。直接用^來表示開頭,$表示結尾即可。(換行後無法匹配)“.*”表示除換行符以外的任意一個字符出現0或n次。即匹配中間的全部內容。

其他的就不一一列舉了,自己多多嘗試,收穫的比看到的多。

以上就是正則表達式的基本語法了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章