溫馨提示×

c#正則表達式怎樣匹配郵箱

c#
小樊
85
2024-10-12 16:53:16
欄目: 編程語言

在C#中,你可以使用Regex類來匹配郵箱地址。一個簡單的匹配郵箱的正則表達式是:^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$。這個正則表達式會匹配大多數(shù)常見的電子郵件地址格式。

以下是一個使用這個正則表達式匹配郵箱的C#代碼示例:

using System;
using System.Text.RegularExpressions;

class Program
{
    static void Main()
    {
        string pattern = @"^[\w\.-]+@[\w\.-]+\.\w+$";
        string input = "example@example.com";

        Regex regex = new Regex(pattern);
        bool match = regex.IsMatch(input);

        if (match)
        {
            Console.WriteLine("郵箱地址有效");
        }
        else
        {
            Console.WriteLine("郵箱地址無效");
        }
    }
}

在這個示例中,pattern變量包含了正則表達式,input變量包含了要檢查的字符串。Regex.IsMatch()方法用于檢查輸入字符串是否與正則表達式匹配,返回一個布爾值。

0