數字驗證類
| 用途 | 正則表達式 | 說明 |
| 非負整數(含 0) | ^\d+$ | 正整數 + 0 |
| 正整數 | ^[0-9]*[1-9][0-9]*$ | 不含 0 |
| 非正整數(含 0) | ^((-\d+)|(0+))$ | 負整數 + 0 |
| 負整數 | ^-[0-9]*[1-9][0-9]*$ | 不含 0 |
| 整數 | ^-?\d+$ | 正負整數 + 0 |
| 非負浮點數 | ^\d+(\.\d+)?$ | 正浮點數 + 0 |
| 正浮點數 | ^(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*))$ | 嚴格正浮點數 |
| 非正浮點數 | ^((-\d+(\.\d+)?)|(0+(\.0+)?))$ | 負浮點數 + 0 |
| 負浮點數 | ^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$ | 嚴格負浮點數 |
| 浮點數 | ^(-?\d+)(\.\d+)?$ | 正負浮點數 + 0 |
字符串驗證類
| 用途 | 正則表達式 | 說明 |
| 純英文字母 | ^[A-Za-z]+$ | 26 個字母 |
| 純大寫字母 | ^[A-Z]+$ | |
| 純小寫字母 | ^[a-z]+$ | |
| 字母數字 | ^[A-Za-z0-9]+$ | |
| 字母數字下劃線 | ^\w+$ | \w = [A-Za-z0-9_] |
| Email 地址 | ^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$ | 常用簡化版 |
| URL | ^[a-zA-Z]+://(\w+(-\w+)*)(\.(\w+(-\w+)*))*(\?\S*)?$ | 含協議、域名、查詢串 |
C# 使用範例
using System.Text.RegularExpressions;
public static class RegexHelper
{
public static bool IsEmail(string input)
{
return Regex.IsMatch(input, @"^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$");
}
public static bool IsPositiveInteger(string input)
{
return Regex.IsMatch(input, @"^[0-9]*[1-9][0-9]*$");
}
// 編譯優化(高頻調用)
private static readonly Regex _emailRegex = new Regex(
@"^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$",
RegexOptions.Compiled | RegexOptions.IgnoreCase);
}
進階提示
- Email/URL 驗證:正則難以 100% 覆蓋 RFC 標準,生產環境建議配合
MailAddress、Uri 類驗證
- 效能優化:高頻正則用
RegexOptions.Compiled、靜態唯讀實例
- 安全防禦:避免災難性回溯,輸入長度限制、超時機制(.NET Core 3.0+
Regex.MatchTimeout)
- 可讀性:複雜正則用
RegexOptions.IgnorePatternWhitespace 加註釋分行
總結
17 條正則覆蓋 .NET 開發 90%+ 常見驗證場景。掌握核心語法、善用工具類封裝、注意效能與安全陷阱,能讓數據驗證既精準又高效。