例子:



//匹配的正则表达式,去掉@不影响效果
Regex r = new Regex(@"^[0-9]");
//开始匹配
Match m = r.Match(this.textBox1.Text);
while (m.Success)
{
MessageBox.Show("首位是数字");
return;
}



textBox1中输入的值,首位是不是数字。



小注:



1、IsMatch()方法;IsMatch()方法实际上是一个返回Bool值得方法,如果测试字符满足正则表达式返回True否则返回False。



2、 @符是用来原样输出的@"",两个引号中间的内容会原样输出,不管其中有什么特殊符号。



2、Replace()方法,Replace()方法实际上是一种替换的方法,替换匹配正则表达式匹配模式。



例子:



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace TestRegularExpressions
{
class Program
{
static void Main(string[] args)
{
string RegularText = "\\w{1,}@\\w{1,}\\.";
string groupEmail = "111@126.com";
if (Regex.IsMatch(groupEmail,RegularText))
{
Console.WriteLine(Regex.Replace(groupEmail, "@", "==="));
}
else
{
Console.WriteLine("未匹配成功!");
}
Console.ReadKey();
}
}
}

输出:


正则表达式Regex类常用方法_split

3、Split()方法,Split()方法实际上是拆分的方法,根据匹配正则表达式进行拆分储存在字符串数组中。



例子:



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace TestRegularExpressions
{
class Program
{
static void Main(string[] args)
{
string RegularText = ";";
string groupEmail = "111@126.com;222@126.com;333@126.com;444@126.com;";
string[] Email;
Email = Regex.Split(groupEmail, RegularText);
foreach (string personEmail in Email)
{
Console.WriteLine(personEmail);
}
Console.ReadKey();
}
}
}



输出:

正则表达式Regex类常用方法_Replace_02


小注:


        对于string即字符串,可以使用String.Split 方法,效果一样。例如,去除vsNt中的英文,代码如下:


string[] Au=vsNt.Split(',');

        函数具体细节: ​​点击打开链接​

Split函数小封装:


#region 根据pattern拆分字符串
/// <summary>
/// 根据pattern拆分字符串
/// </summary>
/// <param name="input">待拆分的字符串</param>
/// <param name="pattern">拆分标识符</param>
/// <returns>拆分后数组</returns>
private string[] SplitString(string input, string pattern)
{
string[] Email;
Email = Regex.Split(input, pattern);
return Email;
}
#endregion