正则表达式

正则表达式在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));

实现截图:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值