C#用正則表達(dá)式Regex.Matches 方法檢查字符串中重復(fù)出現(xiàn)的詞
可以將正則表達(dá)式理解為描述某些規(guī)則的工具,使用正則表達(dá)式可以方便地對字符串進(jìn)行查找和替換的操作。
使用正則表達(dá)式用Regex類的Matches方法,可以檢查字符串中重復(fù)出現(xiàn)的詞。
一、Regex.Matches 方法
在輸入字符串中搜索正則表達(dá)式的所有匹配項(xiàng)并返回所有匹配。
1.重載
Matches(String, String, RegexOptions, TimeSpan)
使用指定的匹配選項(xiàng)和超時(shí)間隔在指定的輸入字符串中搜索指定的正則表達(dá)式的所有匹配項(xiàng)。
Matches(String, String, RegexOptions)
使用指定的匹配選項(xiàng)在指定的輸入字符串中搜索指定的正則表達(dá)式的所有匹配項(xiàng)。
Matches(String, Int32)
從字符串中的指定起始位置開始,在指定的輸入字符串中搜索正則表達(dá)式的所有匹配項(xiàng)。
Matches(String)
在指定的輸入字符串中搜索正則表達(dá)式的所有匹配項(xiàng)。
Matches(String, String)
在指定的輸入字符串中搜索指定的正則表達(dá)式的所有匹配項(xiàng)。
二、Matches(String, String, RegexOptions, TimeSpan)
使用指定的匹配選項(xiàng)和超時(shí)間隔在指定的輸入字符串中搜索指定的正則表達(dá)式的所有匹配項(xiàng)。
1.定義
using System.Text.RegularExpressions; public static MatchCollection Matches(string input, string pattern, RegexOptions options, TimeSpan matchTimeout); 參數(shù) input String 要搜索匹配項(xiàng)的字符串。 pattern String 要匹配的正則表達(dá)式模式。 options RegexOptions 枚舉值的按位組合,這些枚舉值指定用于匹配的選項(xiàng)。 matchTimeout TimeSpan 超時(shí)間隔;若要指示該方法不應(yīng)超時(shí),則為 InfiniteMatchTimeout。 返回 MatchCollection 搜索操作找到的 Match 對象的集合。 如果未找到匹配項(xiàng),則此方法將返回一個(gè)空集合對象。 例外 ArgumentException 出現(xiàn)正則表達(dá)式分析錯(cuò)誤。 ArgumentNullException input 或 pattern 為 null。 ArgumentOutOfRangeException options 不是 RegexOptions 值的有效按位組合。 - 或 - matchTimeout 為負(fù)、零或大于 24 天左右。
2.示例
// 調(diào)用 Matches(String, String, RegexOptions, TimeSpan) 方法 // 以執(zhí)行區(qū)分大小寫的比較,該比較匹配以“es”結(jié)尾的句子中的任何單詞。 // 然后, 調(diào)用Matches(String, String, RegexOptions, TimeSpan) 方法 // 對模式與輸入字符串執(zhí)行不區(qū)分大小寫的比較。 // 在這兩種情況下,超時(shí)間隔都設(shè)置為 1 秒。 // 這兩種方法返回不同的結(jié)果。 using System.Text.RegularExpressions; namespace _084_1 { public class Example { public static void Main() { string pattern = @"\b\w+es\b"; string sentence = "NOTES: Any notes or comments are optional."; // 調(diào)用方法不區(qū)分大小寫 try { foreach (Match match in Regex.Matches(sentence, pattern, RegexOptions.None, TimeSpan.FromSeconds(1)).Cast<Match>()) Console.WriteLine("Found '{0}' at position {1}", match.Value, match.Index); } catch (RegexMatchTimeoutException) { // Do Nothing: Assume that timeout represents no match. } Console.WriteLine(); // 調(diào)用方法區(qū)分大小寫 try { foreach (Match match in Regex.Matches(sentence, pattern, RegexOptions.IgnoreCase).Cast<Match>()) Console.WriteLine("Found '{0}' at position {1}", match.Value, match.Index); } catch (RegexMatchTimeoutException) { } } } } // 運(yùn)行結(jié)果: /* Found 'notes' at position 11 Found 'NOTES' at position 0 Found 'notes' at position 11 */
其中,正則表達(dá)式模式 \b\w+es\b 的定義:\b代表在單詞邊界處開始匹配。\w+代表匹配一個(gè)或多個(gè)單詞字符。es代表匹配單詞尾文本字符串“es”。\b代表在單詞邊界處結(jié)束匹配。
三、Matches(String, String, RegexOptions)
使用指定的匹配選項(xiàng)在指定的輸入字符串中搜索指定的正則表達(dá)式的所有匹配項(xiàng)。
1.定義
using System.Text.RegularExpressions; public static MatchCollection Matches (string input, string pattern, RegexOptions options); 參數(shù) input String 要搜索匹配項(xiàng)的字符串。 pattern String 要匹配的正則表達(dá)式模式。 options RegexOptions 枚舉值的按位組合,這些枚舉值指定用于匹配的選項(xiàng)。 返回 MatchCollection 搜索操作找到的 Match 對象的集合。 如果未找到匹配項(xiàng),則此方法將返回一個(gè)空集合對象。 例外 ArgumentException 出現(xiàn)正則表達(dá)式分析錯(cuò)誤。 ArgumentNullException input 或 pattern 為 null。 ArgumentOutOfRangeException options 不是 RegexOptions 值的有效按位組合。
2.示例
// 調(diào)用 Matches(String, String) 方法以標(biāo)識以“es”結(jié)尾的句子中的任何單詞, // 再調(diào)用 Matches(String, String, RegexOptions) 方法對模式與輸入字符串執(zhí)行不區(qū)分大小寫的比較。 // 這兩種方法返回不同的結(jié)果。 using System.Text.RegularExpressions; namespace _084_2 { public class Example { public static void Main() { string pattern = @"\b\w+es\b"; string sentence = "NOTES: Any notes or comments are optional."; // 調(diào)用方法并區(qū)別大小寫 foreach (Match match in Regex.Matches(sentence, pattern).Cast<Match>()) Console.WriteLine("Found '{0}' at position {1}", match.Value, match.Index); Console.WriteLine(); // 調(diào)用方法并不區(qū)別大小寫 foreach (Match match in Regex.Matches(sentence, pattern, RegexOptions.IgnoreCase).Cast<Match>()) Console.WriteLine("Found '{0}' at position {1}", match.Value, match.Index); } } } // 運(yùn)行結(jié)果: /* Found 'notes' at position 11 Found 'NOTES' at position 0 Found 'notes' at position 11 */
3.示例:用正則表達(dá)式檢查字符串中重復(fù)出現(xiàn)的詞
// 用正則表達(dá)式檢查字符串中重復(fù)出現(xiàn)的詞 using System.Text.RegularExpressions; namespace _084 { public partial class Form1 : Form { private GroupBox? groupBox1; private Label? label1; private Button? button1; public Form1() { InitializeComponent(); Load += Form1_Load; } private void Form1_Load(object? sender, EventArgs e) { // // label1 // label1 = new Label { AutoSize = true, Location = new Point(16, 31), Name = "label1", Size = new Size(43, 17), TabIndex = 1, Text = "label1" }; // // button1 // button1 = new Button { Location = new Point(151, 70), Name = "button1", Size = new Size(75, 23), TabIndex = 2, Text = "檢查", UseVisualStyleBackColor = true }; button1.Click += Button1_Click; // // groupBox1 // groupBox1 = new GroupBox { Location = new Point(12, 12), Name = "groupBox1", Size = new Size(380, 99), TabIndex = 0, TabStop = false, Text = "檢查字符串重復(fù)詞" }; groupBox1.Controls.Add(label1); groupBox1.Controls.Add(button1); groupBox1.SuspendLayout(); // // Form1 // AutoScaleDimensions = new SizeF(7F, 17F); AutoScaleMode = AutoScaleMode.Font; ClientSize = new Size(404, 123); Controls.Add(groupBox1); Name = "Form1"; StartPosition = FormStartPosition.CenterScreen; Text = "檢查字符串中重復(fù)出現(xiàn)的詞"; groupBox1.ResumeLayout(false); groupBox1.PerformLayout(); label1!.Text = "The the quick brown fox fox jumped over the lazy dog dog."; } /// <summary> /// 使用正則表達(dá)式查找重復(fù)出現(xiàn)單詞的集合 /// 如果集合中有內(nèi)容遍歷集合,獲取重復(fù)出現(xiàn)的單詞 /// </summary> private void Button1_Click(object? sender, EventArgs e) { MatchCollection matches = MyRegex().Matches(label1!.Text); if (matches.Count != 0) { //第一種等效foreach,LINQ foreach (var word in from Match match in matches.Cast<Match>()//Cast強(qiáng)制顯示轉(zhuǎn)換 let word = match.Groups["word"].Value select word) { MessageBox.Show(word.ToString(), "英文單詞"); } 第二種等效foreach //foreach (Match match in matches.Cast<Match>()) //{ // string word = match.Groups["word"].Value; // MessageBox.Show(word.ToString(), "英文單詞"); //} 第三種等效for //for (int i = 0; i < matches.Count; i++) //{ // Match match = matches[i]; // string word = match.Groups["word"].Value; // MessageBox.Show(word.ToString(), "英文單詞"); //} } else { MessageBox.Show("沒有重復(fù)的單詞"); } } [GeneratedRegex(@"\b(?<word>\w+)\s+(\k<word>)\b", RegexOptions.IgnoreCase | RegexOptions.Compiled, "zh-CN")] private static partial Regex MyRegex(); } }
四、Matches(String, Int32)
從字符串中的指定起始位置開始,在指定的輸入字符串中搜索正則表達(dá)式的所有匹配項(xiàng)。
1.定義
using System.Text.RegularExpressions; public MatchCollection Matches (string input, int startat); 參數(shù) input String 要搜索匹配項(xiàng)的字符串。 startat Int32 在輸入字符串中開始搜索的字符位置。 返回 MatchCollection 搜索操作找到的 Match 對象的集合。 如果未找到匹配項(xiàng),則此方法將返回一個(gè)空集合對象。 例外 ArgumentNullException input 為 null。 ArgumentOutOfRangeException startat 小于零或大于 input 的長度。
2.示例
// 使用 Match(String) 方法查找以“es”結(jié)尾的句子中的第一個(gè)單詞, // 然后調(diào)用 Matches(String, Int32) 方法以標(biāo)識以“es”結(jié)尾的任何其他單詞。 using System.Text.RegularExpressions; namespace _084_3 { public class Example { public static void Main() { string pattern = @"\b\w+es\b"; Regex regex = new(pattern); string sentence = "Who writes these notes and uses our paper?"; // Get the first match. Match match = regex.Match(sentence); if (match.Success) { Console.WriteLine("Found first 'es' in '{0}' at position {1}", match.Value, match.Index); // Get any additional matches. foreach (Match m in regex.Matches(sentence, match.Index + match.Length).Cast<Match>()) Console.WriteLine("Also found '{0}' at position {1}", m.Value, m.Index); } } } } // 運(yùn)行結(jié)果: /* Found first 'es' in 'writes' at position 4 Also found 'notes' at position 17 Also found 'uses' at position 27 */
五、Matches(String)
在指定的輸入字符串中搜索正則表達(dá)式的所有匹配項(xiàng)。
using System.Text.RegularExpressions; public MatchCollection Matches (string input); 參數(shù) input String 要搜索匹配項(xiàng)的字符串。 返回 MatchCollection 搜索操作找到的 Match 對象的集合。 如果未找到匹配項(xiàng),則此方法將返回一個(gè)空集合對象。 例外 ArgumentNullException input 為 null。
六、Matches(String, String)
在指定的輸入字符串中搜索指定的正則表達(dá)式的所有匹配項(xiàng)。
1.定義
using System.Text.RegularExpressions; public static MatchCollection Matches (string input, string pattern); 參數(shù) input String 要搜索匹配項(xiàng)的字符串。 pattern String 要匹配的正則表達(dá)式模式。 返回 MatchCollection 搜索操作找到的 Match 對象的集合。 如果未找到匹配項(xiàng),則此方法將返回一個(gè)空集合對象。 例外 ArgumentException 出現(xiàn)正則表達(dá)式分析錯(cuò)誤。 ArgumentNullException input 或 pattern 為 null。
2.源碼
// 使用 Matches(String, String) 方法標(biāo)識以“es”結(jié)尾的句子中的任何單詞。 // 使用 Matches(String) 方法標(biāo)識以“es”結(jié)尾的句子中的任何單詞。 using System.Text.RegularExpressions; namespace _084_4 { public class Example { /// <summary> /// Matches(sentence, pattern)是靜態(tài)方法 /// Matches(sentence)不支持靜態(tài)方法 /// </summary> public static void Main() { string pattern = @"\b\w+es\b"; string sentence = "Who writes these notes?"; foreach (Match match in Regex.Matches(sentence, pattern).Cast<Match>()) Console.WriteLine("Found '{0}' at position {1}", match.Value, match.Index); Console.WriteLine("****************************"); Regex regex = new(pattern); foreach (Match match in regex.Matches(sentence).Cast<Match>()) Console.WriteLine("Found '{0}' at position {1}", match.Value, match.Index); } } } // 運(yùn)行結(jié)果: /* Found 'writes' at position 4 Found 'notes' at position 17 **************************** Found 'writes' at position 4 Found 'notes' at position 17 */
到此這篇關(guān)于C#用正則表達(dá)式Regex.Matches 方法檢查字符串中重復(fù)出現(xiàn)的詞的文章就介紹到這了,更多相關(guān)C#正則表達(dá)式檢查重復(fù)出現(xiàn)的詞內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
WPF+SkiaSharp實(shí)現(xiàn)自繪投籃小游戲
這篇文章主要介紹了如何利用WPF+SkiaSharp實(shí)現(xiàn)自繪投籃小游戲。此案例主要是針對光線投影法碰撞檢測功能的示例,順便做成了一個(gè)小游戲,很簡單,但是,效果卻很不錯(cuò),感興趣的可以動手嘗試一下2022-08-08.net(c#)中的new關(guān)鍵字詳細(xì)介紹
在 C# 中,new 關(guān)鍵字可用作運(yùn)算符、修飾符或約束2013-10-10C#實(shí)現(xiàn)的Socket服務(wù)器端、客戶端代碼分享
這篇文章主要介紹了C#實(shí)現(xiàn)的Socket服務(wù)器端、客戶端代碼分享,2個(gè)非常簡單的入門例子,需要的朋友可以參考下2014-08-08C#基于Socket的網(wǎng)絡(luò)通信類你了解嗎
這篇文章主要為大家詳細(xì)介紹了C#基于Socket的網(wǎng)絡(luò)通信類,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助2022-03-03C# 中 System.Index 結(jié)構(gòu)體和 Hat 運(yùn)算符(^)的使用示例
這篇文章主要介紹了C# 中 System.Index 結(jié)構(gòu)體和 Hat 運(yùn)算符(^)的使用示例,幫助大家更好的理解和使用C#,感興趣的朋友可以了解下2020-09-09C# 利用代理爬蟲網(wǎng)頁的實(shí)現(xiàn)方法
這篇文章主要介紹了C# 利用代理爬網(wǎng)頁的實(shí)現(xiàn)方法的相關(guān)資料,希望通過本能幫助到大家實(shí)現(xiàn)這樣的功能,需要的朋友可以參考下2017-10-10