C#正則表達(dá)式Regex用法詳解
一、正則表達(dá)式應(yīng)用舉例
1、C#校驗(yàn)合法性:
if (!Regex.IsMatch(this.txtCode.Text.Trim(), @"^[0-9]*$", RegexOptions.Singleline)) Console.Write("只能輸入數(shù)字");
2、C#限制輸入
輸入除了數(shù)字之外的所有非法字符的判斷
private void textBox1_KeyPress(object sender, KeyPressEventArgs e) { //退格鍵(8)、 回車(13)、全選(1)、復(fù)制(3)、粘貼(22) e.Handled = !(Regex.IsMatch(e.KeyChar, @"\d", RegexOptions.Singleline) || e.KeyChar == (char)8 || e.KeyChar != (char)13); }
粘貼時(shí)過濾不是數(shù)字的字符
private void textbox1_TextChanged(object sender, EventArgs e) { var reg = new Regex("^[0-9]*$"); var str = textbox1.Text.Trim(); var sb = new StringBuilder(); if (!reg.IsMatch(str)) { for (int i = 0; i < str.Length; i++) { if (reg.IsMatch(str[i].ToString())) { sb.Append(str[i].ToString()); } } textbox1.Text = sb.ToString(); //定義輸入焦點(diǎn)在最后一個(gè)字符 textbox1.SelectionStart = textbox1.Text.Length; } }
3、正則表達(dá)式匹配閉合HTML標(biāo)簽(支持嵌套)
1、分組構(gòu)造
分組構(gòu)造描述了正則表達(dá)式的子表達(dá)式,通常用于捕獲輸入字符串的子字符串。 分組構(gòu)造包括下表中列出的語言元素。 有關(guān)詳細(xì)信息,請(qǐng)參閱 分組構(gòu)造。
分組構(gòu)造 | 描述 | 模式 | 匹配 |
---|---|---|---|
( subexpression ) | 捕獲匹配的子表達(dá)式并將其分配到一個(gè)從 1 開始的序號(hào)中。 | (\w)\1 | "deep" 中的 "ee" |
(?< name >subexpression ???????) | 將匹配的子表達(dá)式捕獲到一個(gè)命名組中。 | (?<double>\w)\k<double> | "deep" 中的 "ee" |
(?< name1 -name2 >subexpression ) | 定義平衡組定義。 有關(guān)詳細(xì)信息,請(qǐng)參閱 分組構(gòu)造中的"平衡組定義"部分。 | (((?'Open'\()[^\(\)]*)+((?'Close-Open'\))[^\(\)]*)+)*(?(Open)(?!))$ | "3+2^((1-3)*(3-1))" 中的 "((1-3)*(3-1))" |
(?:subexpression ) | 定義非捕獲組。 | Write(?:Line)? | "Console.WriteLine()" 中的 "WriteLine" "Console.Write(value)" 中的 "Write" |
(?imnsx-imnsx:subexpression ) | 應(yīng)用或禁用 子表達(dá)式中指定的選項(xiàng)。 有關(guān)詳細(xì)信息,請(qǐng)參閱 正則表達(dá)式選項(xiàng)。 | A\d{2}(?i:\w+)\b | "A12xl A12XL a12xl" 中的 "A12xl" 和 "A12XL" |
(?=subexpression ) | 零寬度正預(yù)測(cè)先行斷言。 | \w+(?=\.) | "He is. The dog ran. The sun is out."中的 "is"、"ran" 和 "out" |
(?!subexpression ) | 零寬度負(fù)預(yù)測(cè)先行斷言。 | \b(?!un)\w+\b | "unsure sure unity used" 中的 "sure"和 "used" |
(?<=subexpression ) | 零寬度正回顧后發(fā)斷言。 | (?<=19)\d{2}\b | "1851 1999 1950 1905 2003" 中的 "99"、"50" 和 "05" |
(?<!subexpression ) | 零寬度負(fù)回顧后發(fā)斷言。 | (?<!19)\d{2}\b | "1851 1999 1950 1905 2003" 中的 "51"和 "03" |
(?>subexpression ) | 原子組。 | [13579](?>A+B+) | "1ABB 3ABBC 5AB 5AC" 中的 "1ABB"、"3ABB" 和 "5AB" |
2、舉例:
1、匹配帶有Class的div標(biāo)簽:
<(?i)div[^>]*(?i)class=["']?.+["']?[\s\S]*>[^<>]*(((?'Open'<(?i)div[^>]*>)[^<>]*)+((?'-Open'</(?i)div>)[^<>]*)+)*(?(Open)(?!))</(?i)div>
文本:
<div class="codeHeader" id="code-try-5" data-bi-name="code-header"><span class="language">CSHTML</span><button type="button" class="action is-relative" data-bi-name="copy" aria-label="復(fù)制代碼"></button> <span class="icon"> <span class="docon docon-edit-copy" role="presentation"></span> </span> <span>復(fù)制</span> <div class="successful-copy-alert is-absolute has-right-zero has-top-zero has-left-zero has-bottom-zero is-flex has-flex-align-items-center has-flex-justify-content-center has-text-success-invert has-background-success is-transparent" aria-hidden="true"> <span class="icon is-size-4"> <span class="docon docon-check-mark" role="presentation"></span> </span> </div> </div>
2、匹配class以successful開頭的的div
<(?i)div[^>]*(?i)class=["']?successful.+["']?[\s\S]*>[^<>]*(((?'Open'<(?i)div[^>]*>)[^<>]*)+((?'-Open'</(?i)div>)[^<>]*)+)*(?(Open)(?!))</(?i)div>
3、匹配所有span標(biāo)簽
<(?i)span[^>]*>[^<>]*(((?'Open'<(?i)span[^>]*>)[^<>]*)+((?'-Open'</(?i)span>)[^<>]*)+)*(?(Open)(?!))</(?i)span>
二、.Net正則表達(dá)式測(cè)試器
網(wǎng)頁版本工具:http://tools.jb51.net/regex
下載版:http://www.dbjr.com.cn/softs/61022.html
1、功能簡介
- 自動(dòng)加載上次關(guān)閉前運(yùn)行的最后一組數(shù)據(jù)
- 支持樹形,表格, 文本等三種結(jié)果查看方式
- 支持快捷鍵操作(F5運(yùn)行, F4切換查詢替換模式, F6切換結(jié)果顯示方式, F2復(fù)制代碼, Ctrl+Tab切換焦點(diǎn))
- 選中樹結(jié)點(diǎn)或單元格時(shí)自動(dòng)選中源文本中對(duì)應(yīng)的部分
- 表格內(nèi)容可自由選擇, 自由復(fù)制
- 表格內(nèi)容可導(dǎo)出為csv/xlsx文件
- 支持拖入文件作為匹配源文本
- 支持忽略大小寫,單行模式,多行模式,忽略空白,顯式匹配, ECMAScript等各種選項(xiàng)
- 可解析類似
new Regex("abc", RegexOptions.Singleline | RegexOptions.Multiline)
格式的C#代碼 - 支持生成并拷貝C#代碼到系統(tǒng)剪切板
2、下載與安裝
你可以使用以下兩種方式中的任意一個(gè)來下載安裝正則表達(dá)式測(cè)試器.
安裝版: 下載 Regester安裝程序,解壓后運(yùn)行 RegesterSetup.zh.exe
綠色版: 下載 Regester,解壓后運(yùn)行 Regester.exe,如果無法啟動(dòng),請(qǐng)自行下載安裝 Microsoft .Net Framework 4.5 后再試
3、界面截圖
三、.NET正則表達(dá)式Regex
在C#中,要使用正則表達(dá)式類,請(qǐng)?jiān)谠次募_頭處添加以下語句:
using System.Text.RegularExpressions;
可參考微軟文檔 :.NET 正則表達(dá)式
1、IsMatch(Input,patter[,options]) 否則匹配
如果表達(dá)式在字符串中匹配,返回布爾值。
if (Regex.IsMatch("a.b.c.d", @"(\w)\.(\w)", RegexOptions.IgnoreCase)) Console.Write("匹配成功");
1、正則表達(dá)式選項(xiàng):RegexOptions
有如下選項(xiàng)
RegexOptions枚舉值 | 內(nèi)聯(lián)標(biāo)志 | 簡單說明 |
ExplicitCapture | n | 只有定義了命名或編號(hào)的組才捕獲 |
IgnoreCase | i | 不區(qū)分大小寫 |
IgnorePatternWhitespace | x | 消除模式中的非轉(zhuǎn)義空白并啟用由 # 標(biāo)記的注釋。 |
MultiLine | m | 多行模式,其原理是修改了^和$的含義 |
SingleLine | s | 單行模式,和MultiLine相對(duì)應(yīng) |
2、內(nèi)聯(lián)標(biāo)志
相對(duì)于用RegexOptions在new Regex時(shí)定義Regex表達(dá)式的全局選項(xiàng)來說,內(nèi)聯(lián)標(biāo)志可以更小粒度(以組為單位)的定義匹配選項(xiàng),從而更方便表達(dá)我們的思想。
\bA(?i)b\w+\b 匹配“ABA Able Act”中的“ABA”和“Able”
2、Match(Input,patter[,options]) 單個(gè)匹配
如果在輸入字符串中發(fā)現(xiàn)匹配,則返回匹配對(duì)象。(返回單個(gè)匹配對(duì)象)
Match m = Regex.Match("a.b.c.d", @"(\w)\.(\w)"); if (m.Success) Console.Write("Match=" + m.Value + " pos:" + m.Index); //Match=a.b pos:0
3、Matches(Input,patter[,options]) 多個(gè)匹配
如果在輸入字符串中發(fā)現(xiàn)全部匹配,則返回匹配集合對(duì)象。(返回多個(gè)匹配對(duì)象)
注意:匹配是不能重疊的,如果有重疊,在默認(rèn)情況下,就選擇最長的匹配(除非元字符后加問號(hào))。
Regex的Match()或Matches()=>Match匹配(MatchCollection)=>Group 組(GroupCollection子模式)=>Capture捕獲(CaptureCollection)
MatchCollection mc = Regex.Matches("a.b.c.d", @"(\w)\.(\w)"); for (int i = 0; i < mc.Count; i++) { Match match = mc[i]; Console.WriteLine("Match=" + match.Value + " :" + i); for (int j = 0; j < match.Groups.Count; j++) { Group group = match.Groups[j]; Console.WriteLine("--Group =" + group.Value + " :" + j); for (int k = 0; k < group.Captures.Count; k++) { Console.WriteLine("------Captures =" + group.Captures[k].Value + " :" + k); } } }
結(jié)果如下:
Match=a.b :0
----Group =a.b :0
--------Captures =a.b :0
----Group =a :1
--------Captures =a :0
----Group =b :2
--------Captures =b :0
Match=c.d :1
----Group =c.d :0
--------Captures =c.d :0
----Group =c :1
--------Captures =c :0
----Group =d :2
--------Captures =d :0
返回匹配成功后的第一個(gè)子模式的值:
var mc = Regex.Matches(Server.UrlDecode(client.ResponseHeaders["Content-Disposition"]), @"filename=(.+)"); string filename = mc[0].Groups[1].Value;
4、Replace(Input,patter,replacement或evaluator [,options]) 替換
用給定的Replacement替換input中的匹配。
Console.WriteLine(Regex.Replace("this test*", "[^a-zA-Z]", "()")); //this()test() Console.WriteLine(Regex.Replace("sevenyear", @"\w+", m => { return m.Value.ToUpper(); }) ); //SEVENYEAR
5、Split(Input,patter[,options]) 拆分
在由模式定義的位置拆分input,返回string[]
string[] s = Regex.Split("first-second-thrid", "-"); for (int i = 0; i < s.Length; i++) { Console.WriteLine(s[i]); } //first //second //thrid
1、每4個(gè)長度進(jìn)行分割
var temp = Regex.Split("1234abcdef", @"(?<=\G.{4})(?!$)"); temp.ToList().ForEach(t => Console.WriteLine(t)); //1234 //abcd //ef
2、提取單詞
var temp = Regex.Split("1234 abcd efa", @"(?<=\S+\b\s+)"); temp.ToList().ForEach(t => Console.WriteLine(t)); //1234 //abcd //ef
3、每兩個(gè)單詞進(jìn)行分割
var temp = Regex.Split("1234,abcd,12345,abcd,ab", @"(?<=\G(?:\w+[,,]){2})"); temp.ToList().ForEach(t => Console.WriteLine(t)); //1234,abcd, //12345,abcd, //ab
6、實(shí)例化Regex類
Regex exp= new Regex(@"\w\.\w", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace); MatchCollection mc = exp.Matches("a.b.c.d");
實(shí)例:
void Main() { string ss = "259年又62天"; MatchCollection mc = Regex.Matches(ss, @"(?:(?<year>\d+)年)?又?(?:(?<month>\d+)天)?"); for (int i = 0; i < mc.Count; i++) { Match match = mc[i]; Console.WriteLine("Match[" + i + "],Value:" + match.Value); for (int j = 0; j < match.Groups.Count; j++) { Group group = match.Groups[j]; Console.WriteLine("--Group[" + j + "],Name:" + group.Name + " ,Value:" + group.Value); for (int k = 0; k < group.Captures.Count; k++) { Console.WriteLine("------Captures[" + k + "],Value:" + group.Captures[k].Value); } } Console.WriteLine(); } }
Match[0],Value:259年又62天
--Group[0],Name:0 ,Value:259年又62天
------Captures[0],Value:259年又62天
--Group[1],Name:year ,Value:259
------Captures[0],Value:259
--Group[2],Name:month ,Value:62
------Captures[0],Value:62
Match[1],Value:
--Group[0],Name:0 ,Value:
------Captures[0],Value:
--Group[1],Name:year ,Value:
--Group[2],Name:month ,Value:
到此這篇關(guān)于C#正則表達(dá)式Regex用法的文章就介紹到這了。希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
C#基礎(chǔ)教程之IComparable用法,實(shí)現(xiàn)List<T>.sort()排序
這篇文章主要介紹了C#的一些基礎(chǔ)知識(shí),主要是IComparable用法,實(shí)現(xiàn)List<T>.sort()排序,非常的實(shí)用,這里推薦給大家。2015-02-02C#利用DesignSurface如何實(shí)現(xiàn)簡單的窗體設(shè)計(jì)器
這篇文章主要介紹了C#利用DesignSurface如何實(shí)現(xiàn)簡單窗體設(shè)計(jì)器的相關(guān)資料,文中通過圖文及示例代碼介紹的很詳細(xì),對(duì)大家具有一定的參考價(jià)值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧。2017-02-02C#使用迭代法實(shí)現(xiàn)Fibnaci數(shù)列
這篇文章主要介紹了C#使用迭代法實(shí)現(xiàn)Fibnaci數(shù)列的方法,較為詳細(xì)的分析了Fibnaci數(shù)列的原理與迭代法實(shí)現(xiàn)技巧,需要的朋友可以參考下2015-05-05詳細(xì)介紹C#之文件校驗(yàn)工具的開發(fā)及問題
目前校驗(yàn)文件使用最多的是MD值和SHA值,不外乎有些使用CRC,前段時(shí)間微軟發(fā)布了VisualStudio正式版,win鏡像,微軟官方給出的校驗(yàn)方式都是校驗(yàn)文件的SHA值。下面詳細(xì)介紹C#之文件校驗(yàn)工具的開發(fā)及問題,需要的朋友可以參考下2015-07-07C#模擬MSN窗體抖動(dòng)的實(shí)現(xiàn)代碼
這篇文章主要介紹了C#模擬MSN窗體抖動(dòng)的實(shí)現(xiàn)代碼,非常實(shí)用的一個(gè)功能,需要的朋友可以參考下2014-08-08C#實(shí)現(xiàn)讀取和設(shè)置文件與文件夾的權(quán)限
這篇文章主要為大家詳細(xì)介紹了如何使用C#實(shí)現(xiàn)讀取和設(shè)置文件與文件夾的權(quán)限,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-03-03