正则表达式的基本语法。
当然,和平常惯例一样,正则表达式也有预定义字符集。有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次。即匹配中间的全部内容。
其他的就不一一列举了,自己多多尝试,收获的比看到的多。
以上就是正则表达式的基本语法了。