C# 數(shù)據(jù)驗證Regex示例詳解
更新時間:2025年02月12日 09:42:27 作者:幻想趾于現(xiàn)實
文章介紹了C#中使用Regex進行數(shù)據(jù)驗證的方法,包括整數(shù)和小數(shù)的正負驗證,以及郵箱和身份證號的格式驗證,感興趣的朋友一起看看吧
Regular Expression,簡稱 Regex,是一種用于匹配和處理文本的強大工具。它通過定義特定的模式,可以用來搜索、替換或提取字符串中的特定內容。
先引入命名空間
using System.Text.RegularExpressions;
Intege(整數(shù))
必須是正整數(shù)
//必須是正整數(shù) public static bool IsPositiveInteger(string txt) { Regex objReg = new Regex(@"^[1-9]\d*$"); return objReg.IsMatch(txt); }
正整數(shù)和零
public static bool IsPositiveIntegerAndZero(string txt) { Regex objReg = new Regex(@"^[1-9]\d*|0$"); return objReg.IsMatch(txt); }
負整數(shù)
public static bool IsNegativeInteger(string txt) { Regex objReg = new Regex(@"^-[1-9]\d*$"); return objReg.IsMatch(txt); }
正負均可
public static bool IsInteger(string txt) { Regex objReg = new Regex(@"^-?[1-9]\d*$"); return objReg.IsMatch(txt); }
Decimal(小數(shù))
正數(shù)
public static bool IsPositiveDecimal(string txt) { Regex objReg = new Regex(@"^[1-9]\d*\.\d*|0\.\d*[1-9]\d*$"); return objReg.IsMatch(txt); }
負數(shù)
public static bool IsNegativeDecimal(string txt) { Regex objReg = new Regex(@"^-([1-9]\d*\.\d*|0\.\d*[1-9]\d*)$"); return objReg.IsMatch(txt); }
正負均可
public static bool IsDecimal(string txt) { Regex objReg = new Regex(@"^-?([1-9]\d*\.\d*|0\.\d*[1-9]\d*|0?\.0+|0)$"); return objReg.IsMatch(txt); }
其他驗證
郵箱
public static bool IsEmail(string txt) { Regex objReg = new Regex(@"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"); return objReg.IsMatch(txt); }
身份證
public static bool IsIdentityCard(string txt) { Regex objReg = new Regex(@"^(\d{15}$|^\d{18}$|^\d{17}(\d|X|x))$"); return objReg.IsMatch(txt); }
郵箱編碼
public static bool IsPostalCode(string txt) { if (txt.Length != 6) return false; Regex objReg = new Regex(@"[1-9]\d{5}(?!\d)"); return objReg.IsMatch(txt); }
到此這篇關于C# 數(shù)據(jù)驗證Regex的文章就介紹到這了,更多相關C# 數(shù)據(jù)驗證Regex內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
C#遞歸實現(xiàn)顯示文件夾及所有文件并計算其大小的方法
這篇文章主要介紹了C#遞歸實現(xiàn)顯示文件夾及所有文件并計算其大小的方法,是遍歷算法中比較典型的一種應用,有不錯的學習借鑒價值,需要的朋友可以參考下2014-08-08C#使用RichTextBox實現(xiàn)替換文字及改變字體顏色功能示例
這篇文章主要介紹了C#使用RichTextBox實現(xiàn)替換文字及改變字體顏色功能,結合實例形式洗了C#中RichTextBox組件文字替換及改變字體顏色相關操作技巧,需要的朋友可以參考下2019-02-02C#實現(xiàn)將Excel表格轉換為圖片(JPG/?PNG)
Excel表格可能會因為不同設備或字體缺失等問題,導致格式錯亂或數(shù)據(jù)顯示異常,轉換為圖片后,能確保數(shù)據(jù)的排版等保持一致,下面我們看看如何使用C#實現(xiàn)將Excel表格轉換為圖片吧2025-04-04unity實現(xiàn)鼠標經(jīng)過時ui及物體的變色操作
這篇文章主要介紹了unity實現(xiàn)鼠標經(jīng)過時ui及物體的變色操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-04-04