C#正則表達式之Ismatch()的用法解讀
c#正則表達式之ismatch()的用法解讀
c#正則表達式之ismatch()
1.ismatch()方法
ismatch()方法可以測試字符串,看它是否匹配正則表達式的模式。
如果發現一次匹配,該方法返回"true",否則返回"false"。
ismatch()擁有一個靜態的重載方法,使用時無需顯示的創建一個regex對象。
2.regexoptions枚舉
using system; using system.collections.generic; using system.linq; using system.text; using system.text.regularexpressions; using system.threading.tasks; namespace regular { class program { static void main(string[] args) { regex mregular = new regex("a[bcd]c", regexoptions.explicitcapture); //ismatch擁有靜態和非靜態的幾種重載方法; //如果正則表達式只使用一次,使用靜態方法更好! string str = "abc acc"; console.writeline(mregular.ismatch(str)); string str2 = "welcome to verison-fios!"; console.writeline(regex.ismatch(str2,"me t",regexoptions.ignorecase)); console.readkey(); } } }
3.spilt()方法
此方法在每次發現匹配的位置拆分字符串。該方法返回一個字符串數組。
該方法有靜態的重載方法,也有用于regex實例的方法!
c#正則表達式編寫及驗證方式
正則表達式應用很廣泛,應該大多人都接觸過了,這個語法規則既多又凌亂,每次用的時候都得重新看一遍語法,真的是讓人頭疼啊!
但是實際上我們并不要掌握很多的符號用法規則,牢記最常用的幾個就能應付很多場景.
下面我羅列出來我最常用的8個:
- \d 匹配數字
- ^匹配行的開始
- $ 匹配行的結尾
- \ 對下一個字符轉義
- * 匹配前面的表達式零次或多次
- + 匹配前面的表達式一次或多次
- ?匹配前面的表達式零次或一次
- {n,m}m 和 n 均為非負整數,其中n <= m。最少匹配 n 次且最多匹配 m 次。
正則表達式
① [0,1000]:閉合區間0到1000,不包括小數
regexstring=?@"^(0|1000|([1-9]\d{0,2}))$"
②[0,100]:閉區間,包括小數點后三位
regexstring = @"^((\d|[1-9]\d)(\.\d{1,3})?)|100$";//[0,100] 包括小數點后三位
驗證
static void main(string[] args) { string regexstring; //regexstring = @"^(0|1000|([1-9]\d{0,2}))$"; regexstring = @"^((\d|[1-9]\d)(\.\d{1,3})?)|100$";//[0,100] 包括小數點后三位 for (double i = 0; i < 100; i = i + 0.001) { var str = math.round(i, 3).tostring(); bool mathresult = regex.ismatch(str, regexstring); if (!mathresult) { console.writeline(str); } } console.writeline("match complete!"); console.readkey(); }
運行結果:
如果運行錯誤,會輸出沒匹配上的數值,這個說明編寫的正則沒問題!
總結
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持碩編程。