1:Reegx
2:Match
3:MatchCollection
先让我们来看代码,解析在代码中:
- string s = "2222";
- Regex r = new Regex(s); //创建一个Regex对象,支持正则表达式的,比如//s222
- Match m = r.Match("2222sdfsdf");//创建一个Match,当然是通过Regex的Match方法返回实例
- if (m.Success)
- {
- textBox1.Text = m.Index.ToString();//返回找到的开始位置
- }
- MatchCollection mc;//定义MatchCollection对象,这个对象十分有用,可以多次查询
- string[] result = new string[20];
- int[] matchp = new int[20];
- Regex r1 = new Regex("abc");//创建一个Regex对象
- string t = null;
- mc = r1.Matches("11122abc3323abcjdsjksdfabc");//重要,调用Regex的Matches方法,支持多匹配规则
- for (int i = 0; i < mc.Count; i++)//使用了MatchCollection 的Count属性
- {
- result[i] = mc[i].Value;
- matchp[i] = mc[i].Index;
- //t = t + mc[i].Index.ToString();
- t = t + mc[i].Value;
- }
- textBox1.Text = t;
从上面的代码中,我们很明确的知道使用正则的步骤:
1:创建一个正则表达串: string s_Regex = "//tsfsdfjjsadfjdf";
2:使用new创建一个Regex对象,并将s_Regex作为参数(当然还有别的方法)
3:定义一个Match或者MatchCollection或者GroupCollection ,CaptureCollection, Capture
4:使用Regex对象的Match或者Matches方法来获取结果
5:通过Match来获取位置信息。