正則表達式

正則表達式在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));

實現截圖:
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章