C# 正則表達式 Regex

判斷是否符合 正則表達式

    
var input = "0912345678";
var regex = new Regex(@"^09\d{8}$"); // 字串必須要 09 開頭,且後面有 8 個數字做結尾

if (regex.IsMatch(input)) // 判斷是否符合正則表達式
{
    Console.WriteLine("符合");
}
else
{
    Console.WriteLine("不符合");
}
    

取出符合正則表達式的第一組資料

    
var input = "0912345678, 0987654321";
var regex = new Regex(@"09\d{8}");

var match = regex.Match(input);
if (match.Success) // 是否有符合的內容
{
    Console.WriteLine($"符合: {match.Value}");;
}
else
{
    Console.WriteLine("不符合");
}
    

取出符合正則表達式的每一組資料

    
var input = "0912345678, 0987654321";
var regex = new Regex(@"09\d{8}");


var matches = regex.Matches(input);

if (matches.Count == 0)
{
    Console.WriteLine("沒有符合的");
}

foreach (Match match in matches)
{
    Console.WriteLine($"符合: {match.Value}");
}
    

將符合正則表達式的資料取代

方法一:
    

var input = "0912345678, 0987654321";

var result = Regex.Replace(input, @"09\d{8}", "09********");

Console.WriteLine(result);
// 09********, 09********
    

方法二:
    
var input = "0912345678, 0987654321";

var regex = new Regex(@"09\d{8}");
var result = regex.Replace(input, "09********");

Console.WriteLine(result);
// 09********, 09********
    



參考資料:
Microsoft.Learn - Regex.Match Method
Microsoft.Learn - Regex.Matches Method
Microsoft.Learn - Regex.Replace Method

留言

張貼留言

如果有任何問題、建議、想說的話或文章題目推薦,都歡迎留言或來信: a@ruyut.com