正则表达式在C#中的用法
下面为输入任意一串字符串,输出其中的数字或字母
代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;//引入正则表达式的命名空间
namespace Text2
{
class Program
{
static void Main(string[] args)
{
string str = Console.ReadLine();
string patten = @"[A-Za-z0-9]";
MatchCollection math = Regex.Matches(str, patten);
foreach (Match item in math)
{
Console.WriteLine(item);
}
Console.ReadKey();
}
}
}
实现截图:
下面为输出除chou之外的字符全部替换为“*”
代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;//引入正则表达式的命名空间
namespace Text2
{
class Program
{
static void Main(string[] args)
{
string str = "his name is Blue Mini dog!";
string patten = @"[^ahou]";
string res = Regex.Replace(str, patten, "*");
Console.WriteLine(str);
Console.WriteLine(res);
Console.ReadKey();
}
}
}
实现截图:
校验国内电话号码(支持四种写法校验 A. 01087654321 B. (010)87654321 C.01087654321 D.010 87654321)
代码:
string str1 = "010-87654321";
string str2 = "010 87654321";
string str3 = "01087654321";
string str4 = "(010)87654321";
string str5 = "010376543218";
string str6 = "(010-87654321";
string str7 = "01097654321";
string patten = @"^010[-| ]?\d{8}$|^\(010\)\d{8}$";
Console.WriteLine("原号码:" + str1 + "是否满足" + Regex.IsMatch(str1, patten));
Console.WriteLine("原号码:" + str2 + "是否满足" + Regex.IsMatch(str2, patten));
Console.WriteLine("原号码:" + str3 + "是否满足" + Regex.IsMatch(str3, patten));
Console.WriteLine("原号码:" + str4 + "是否满足" + Regex.IsMatch(str4, patten));
Console.WriteLine("原号码:" + str5 + "是否满足" + Regex.IsMatch(str5, patten));
Console.WriteLine("原号码:" + str6 + "是否满足" + Regex.IsMatch(str6, patten));
Console.WriteLine("原号码:" + str7 + "是否满足" + Regex.IsMatch(str7, patten));
实现截图: