一个例子
string value="123"; Regex re=new Regex(^[0-9]{1,2}$); if(!re.IsMatch(value)) { }
上面的代码用来判断字符串以数字开头和结尾,并且最多有2位。
Regex re=new Regex(^[0-9]{1,2}$);
解释:
这句:声明一个新的Regex,
^表示:匹配字符串开始字符
$表示:匹配结尾字符。
[0-9]:匹配的数据类型。和\d异曲同工。
{1,2}:匹配数据重复的次数。在这里表示出现了一次或两次
详解:
一:Regex语法
(1)^、$
匹配数据:1234567;
Regex : ^[0-9]
结果:1
匹配以数字开头的一个字符
数据改为:h123456;
Regex:^[0-9]
结果:无
而当[]里该为a-z;结果就是h了。$和^类似,如下图

另外一种意思,当^在[^n]里面,匹配除了n以为的任意字符
例如
匹配数据:4525
Regex:[^45]
结果:2
(2)[ ]:匹配数据类型
例如
匹配数据:1234567
Regex:\d[0-9]
结果:12、34、56 3组 (7被滤掉)
例如
匹配数据:123d
Regex:\D
结果:d
- (.)点:匹配换行符以外的任意字符
- \w(小写):匹配字母或数字或下划线或汉字
- \s: (小写): 匹配任意的空白符
- \W(大写): 于小写相反
(3){}:匹配数据重复次数
- *表示重复零次或更多次,于\d{0,}(表示0次到无限次)相同
例如:
匹配数据:123K4567
Regex:\d*
结果:123、 、4567(注意中间的空值)
- +表示重复一次或更多次
- ?表示重复一次或零次
- {n}重复n次
例如
匹配数据:123K45678
Regex:\d{4}
结果:4567 (数字在K后有连续出现过4次,在前面没有)
例如
匹配数据:12K45678
Regex:\d{2,3}
结果为:12、456、78 (从多位到少取,从前往后取,字符分开取,揣摩…)
二 Regex在.net上
(1) IsMatch重载列表:(判断是否存在)
- IsMatch(string):判断字符串中是否存在匹配项,实例如开头例子。
- IsMatch(string,int):从指定的开始位置判断是否存在匹配项
- IsMatch(string,string):从外部传递会正则表达式及要匹配的数据,而不是声明的时候定义好正则表达式
- IsMatch(string,string,RegexOptions):在匹配选项下匹配数据
例
1 |
Regex.IsMatch( "www.GOOGLE.com" , "^[a-z.]{1,20}$" , RegexOptions.IgnoreCase)
|
RegexOptions.IgnoreCase:表示不区分大小写
(2)Match(记录匹配到的数据)已重载
1
2
3
4
5
6
7
8 |
string text = "One car red car blue car" ;
string pat = @"(\w+)\s+(car)" ;
Regex r = new Regex(pat, RegexOptions.IgnoreCase);
Match m = r.Match(text);
Console.WriteLine( "{0}" ,m.Value.ToString ());
Console.ReadKey();
|
(3)Replace (替换匹配到的数据)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 |
static void Main( string [] args)
{
string text = "four score and seven years ago" ;
System.Console.WriteLine( "text=[" + text + "]" );
string result = Regex.Replace(text, @"\w+" ,
new MatchEvaluator(Program.CapText));
System.Console.WriteLine( "result=[" + result + "]" );
Console.ReadKey();
}
static string CapText(Match m)
{
string x = m.ToString();
if ( char .IsLower(x[0]))
{
return char .ToUpper(x[0]) + x.Substring(1, x.Length - 1);
}
return x;
}
|
输出

|