正则表达式元字符:
1 中括号[]:用来描述匹配规则,一个中括号只能匹配一个字符
2 小括号():用来描述匹配的字符串,一个小括号表示匹配一段字符串
3 大括号{}:用来描述匹配的具体数量
4 \s :用于匹配单个空格符,包括tab键和换行符
5 \S :用于匹配除单个空格符之外的所有字符
6 \d :用于匹配从0到9的数字
7 \w :用于匹配字母,数字或下划线字符
8 \W :用于匹配所有与\w不匹配的字符
9 . :用于匹配除换行符之外的所有字符
10 ^ :脱字符 匹配一行的开头位置
11 $ :美元符 匹配一行的结束位置
12 ? :容许匹配一次,但非必须
13 * :可以匹配任意多次,也可能不匹配
14 + :至少需要匹配一次,至多可能任意多次
例子:
//影视名称处理
public static string processName(string name)
{
if (string.IsNullOrEmpty(name))
{
return name;
}
//1 把影片名中"第x季"去掉
name = Regex.Replace(name, @"第([\s\S]*)(季|期|集|部)", "");
//2 替换到尾部的年份,比如xx2010,只保留xx
name = Regex.Replace(name, @"(\d{1,4})$", "");
//3 替换xx月的名称,例如:优酷全娱乐20146月
name = Regex.Replace(name, @"(\d{1,10})月", "");
return name;
}
查找一个字符串中所有的数字
String test = "我想80年代的123台";
String pattern = @"[0-9]+";
Regex rgx = new Regex(pattern, RegexOptions.IgnoreCase);
MatchCollection matches = rgx.Matches(test);
if (matches.Count > 0)
{
Console.WriteLine("{0} ({1} matches):", test, matches.Count);
foreach (Match match in matches)
Console.WriteLine(" " + match.Value);
}
延伸阅读:http://www.cnblogs.com/kissdodog/archive/2013/04/25/3043173.html

2164

被折叠的 条评论
为什么被折叠?



