C#用正则表达式Regex.Matches 方法检查字符串中重复出现的词

本文主要是介绍C#用正则表达式Regex.Matches 方法检查字符串中重复出现的词,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

目录

一、Regex.Matches 方法

1.重载 

二、Matches(String, String, RegexOptions, TimeSpan)

1.定义

2.示例

三、Matches(String, String, RegexOptions)

1.定义

2.示例

3.示例:用正则表达式检查字符串中重复出现的词

四、Matches(String, Int32)

1.定义

2.示例

五、Matches(String)

六、Matches(String, String)

1.定义

2.源码 


        可以将正则表达式理解为描述某些规则的工具,使用正则表达式可以方便地对字符串进行查找和替换的操作。

        使用正则表达式用Regex类的Matches方法,可以检查字符串中重复出现的词。

一、Regex.Matches 方法

        在输入字符串中搜索正则表达式的所有匹配项并返回所有匹配。

1.重载 

Matches(String, String, RegexOptions, TimeSpan)

使用指定的匹配选项和超时间隔在指定的输入字符串中搜索指定的正则表达式的所有匹配项。

Matches(String, String, RegexOptions)

使用指定的匹配选项在指定的输入字符串中搜索指定的正则表达式的所有匹配项。

Matches(String, Int32)

从字符串中的指定起始位置开始,在指定的输入字符串中搜索正则表达式的所有匹配项。

Matches(String)

在指定的输入字符串中搜索正则表达式的所有匹配项。

Matches(String, String)

在指定的输入字符串中搜索指定的正则表达式的所有匹配项。

二、Matches(String, String, RegexOptions, TimeSpan)

        使用指定的匹配选项和超时间隔在指定的输入字符串中搜索指定的正则表达式的所有匹配项。

1.定义

using System.Text.RegularExpressions;public static MatchCollection Matches(string input, string pattern, RegexOptions options, TimeSpan matchTimeout);参数
input    String
要搜索匹配项的字符串。pattern    String
要匹配的正则表达式模式。options    RegexOptions
枚举值的按位组合,这些枚举值指定用于匹配的选项。matchTimeout    TimeSpan
超时间隔;若要指示该方法不应超时,则为 InfiniteMatchTimeout。返回    MatchCollection
搜索操作找到的 Match 对象的集合。 如果未找到匹配项,则此方法将返回一个空集合对象。例外
ArgumentException
出现正则表达式分析错误。ArgumentNullException
input 或 pattern 为 null。ArgumentOutOfRangeException
options 不是 RegexOptions 值的有效按位组合。
- 或 -
matchTimeout 为负、零或大于 24 天左右。

2.示例

// 调用 Matches(String, String, RegexOptions, TimeSpan) 方法
// 以执行区分大小写的比较,该比较匹配以“es”结尾的句子中的任何单词。
// 然后, 调用Matches(String, String, RegexOptions, TimeSpan) 方法
// 对模式与输入字符串执行不区分大小写的比较。
// 在这两种情况下,超时间隔都设置为 1 秒。
// 这两种方法返回不同的结果。
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.";// 调用方法不区分大小写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();// 调用方法区分大小写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) { }}}
}
// 运行结果:
/*
Found 'notes' at position 11Found 'NOTES' at position 0
Found 'notes' at position 11*/

        其中,正则表达式模式 \b\w+es\b 的定义:\b代表在单词边界处开始匹配。\w+代表匹配一个或多个单词字符。es代表匹配单词尾文本字符串“es”。\b代表在单词边界处结束匹配。

三、Matches(String, String, RegexOptions)

        使用指定的匹配选项在指定的输入字符串中搜索指定的正则表达式的所有匹配项。

1.定义

using System.Text.RegularExpressions;public static MatchCollection Matches (string input, string pattern, RegexOptions options);参数
input    String
要搜索匹配项的字符串。pattern    String
要匹配的正则表达式模式。options    RegexOptions
枚举值的按位组合,这些枚举值指定用于匹配的选项。返回
MatchCollection
搜索操作找到的 Match 对象的集合。 如果未找到匹配项,则此方法将返回一个空集合对象。例外
ArgumentException
出现正则表达式分析错误。ArgumentNullException
input 或 pattern 为 null。ArgumentOutOfRangeException
options 不是 RegexOptions 值的有效按位组合。

2.示例

// 调用 Matches(String, String) 方法以标识以“es”结尾的句子中的任何单词,
// 再调用 Matches(String, String, RegexOptions) 方法对模式与输入字符串执行不区分大小写的比较。
// 这两种方法返回不同的结果。
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.";// 调用方法并区别大小写foreach (Match match in Regex.Matches(sentence, pattern).Cast<Match>())Console.WriteLine("Found '{0}' at position {1}",match.Value, match.Index);Console.WriteLine();// 调用方法并不区别大小写foreach (Match match in Regex.Matches(sentence, pattern, RegexOptions.IgnoreCase).Cast<Match>())Console.WriteLine("Found '{0}' at position {1}",match.Value, match.Index);}}
}
// 运行结果:
/*
Found 'notes' at position 11Found 'NOTES' at position 0
Found 'notes' at position 11*/ 

3.示例:用正则表达式检查字符串中重复出现的词

// 用正则表达式检查字符串中重复出现的词
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 = "检查字符串重复词"};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 = "检查字符串中重复出现的词";groupBox1.ResumeLayout(false);groupBox1.PerformLayout();label1!.Text = "The the quick brown fox  fox jumped over the lazy dog dog.";}/// <summary>/// 使用正则表达式查找重复出现单词的集合/// 如果集合中有内容遍历集合,获取重复出现的单词/// </summary>private void Button1_Click(object? sender, EventArgs e){MatchCollection matches = MyRegex().Matches(label1!.Text);if (matches.Count != 0){//第一种等效foreach,LINQforeach (var word in from Match match in matches.Cast<Match>()//Cast强制显示转换let word = match.Groups["word"].Valueselect 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("没有重复的单词"); }}[GeneratedRegex(@"\b(?<word>\w+)\s+(\k<word>)\b", RegexOptions.IgnoreCase | RegexOptions.Compiled, "zh-CN")]private static partial Regex MyRegex();}
}

 

四、Matches(String, Int32)

        从字符串中的指定起始位置开始,在指定的输入字符串中搜索正则表达式的所有匹配项。

1.定义

using System.Text.RegularExpressions;
public MatchCollection Matches (string input, int startat);参数
input    String
要搜索匹配项的字符串。startat    Int32
在输入字符串中开始搜索的字符位置。返回
MatchCollection
搜索操作找到的 Match 对象的集合。 如果未找到匹配项,则此方法将返回一个空集合对象。例外
ArgumentNullException
input 为 null。ArgumentOutOfRangeException
startat 小于零或大于 input 的长度。

2.示例

// 使用 Match(String) 方法查找以“es”结尾的句子中的第一个单词,
// 然后调用 Matches(String, Int32) 方法以标识以“es”结尾的任何其他单词。
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);}}}
}
// 运行结果:
/*
Found first 'es' in 'writes' at position 4
Also found 'notes' at position 17
Also found 'uses' at position 27*/

五、Matches(String)

        在指定的输入字符串中搜索正则表达式的所有匹配项。

using  System.Text.RegularExpressions;
public MatchCollection Matches (string input);参数
input    String
要搜索匹配项的字符串。返回
MatchCollection
搜索操作找到的 Match 对象的集合。 如果未找到匹配项,则此方法将返回一个空集合对象。例外
ArgumentNullException
input 为 null。

六、Matches(String, String)

        在指定的输入字符串中搜索指定的正则表达式的所有匹配项。

1.定义

using System.Text.RegularExpressions;
public static MatchCollection Matches (string input, string pattern);参数
input    String
要搜索匹配项的字符串。pattern    String
要匹配的正则表达式模式。返回
MatchCollection
搜索操作找到的 Match 对象的集合。 如果未找到匹配项,则此方法将返回一个空集合对象。例外
ArgumentException
出现正则表达式分析错误。ArgumentNullException
input 或 pattern 为 null。

2.源码 

// 使用 Matches(String, String) 方法标识以“es”结尾的句子中的任何单词。
// 使用 Matches(String) 方法标识以“es”结尾的句子中的任何单词。
using System.Text.RegularExpressions;namespace _084_4
{public class Example{/// <summary>/// Matches(sentence, pattern)是静态方法/// Matches(sentence)不支持静态方法/// </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);}}
}
// 运行结果:
/*
Found 'writes' at position 4
Found 'notes' at position 17
****************************
Found 'writes' at position 4
Found 'notes' at position 17*/

这篇关于C#用正则表达式Regex.Matches 方法检查字符串中重复出现的词的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/670216

相关文章

Windows 上如果忘记了 MySQL 密码 重置密码的两种方法

《Windows上如果忘记了MySQL密码重置密码的两种方法》:本文主要介绍Windows上如果忘记了MySQL密码重置密码的两种方法,本文通过两种方法结合实例代码给大家介绍的非常详细,感... 目录方法 1:以跳过权限验证模式启动 mysql 并重置密码方法 2:使用 my.ini 文件的临时配置在 Wi

Java中字符串转时间与时间转字符串的操作详解

《Java中字符串转时间与时间转字符串的操作详解》Java的java.time包提供了强大的日期和时间处理功能,通过DateTimeFormatter可以轻松地在日期时间对象和字符串之间进行转换,下面... 目录一、字符串转时间(一)使用预定义格式(二)自定义格式二、时间转字符串(一)使用预定义格式(二)自

MySQL重复数据处理的七种高效方法

《MySQL重复数据处理的七种高效方法》你是不是也曾遇到过这样的烦恼:明明系统测试时一切正常,上线后却频频出现重复数据,大批量导数据时,总有那么几条不听话的记录导致整个事务莫名回滚,今天,我就跟大家分... 目录1. 重复数据插入问题分析1.1 问题本质1.2 常见场景图2. 基础解决方案:使用异常捕获3.

最详细安装 PostgreSQL方法及常见问题解决

《最详细安装PostgreSQL方法及常见问题解决》:本文主要介绍最详细安装PostgreSQL方法及常见问题解决,介绍了在Windows系统上安装PostgreSQL及Linux系统上安装Po... 目录一、在 Windows 系统上安装 PostgreSQL1. 下载 PostgreSQL 安装包2.

Python正则表达式语法及re模块中的常用函数详解

《Python正则表达式语法及re模块中的常用函数详解》这篇文章主要给大家介绍了关于Python正则表达式语法及re模块中常用函数的相关资料,正则表达式是一种强大的字符串处理工具,可以用于匹配、切分、... 目录概念、作用和步骤语法re模块中的常用函数总结 概念、作用和步骤概念: 本身也是一个字符串,其中

SQL中redo log 刷⼊磁盘的常见方法

《SQL中redolog刷⼊磁盘的常见方法》本文主要介绍了SQL中redolog刷⼊磁盘的常见方法,将redolog刷入磁盘的方法确保了数据的持久性和一致性,下面就来具体介绍一下,感兴趣的可以了解... 目录Redo Log 刷入磁盘的方法Redo Log 刷入磁盘的过程代码示例(伪代码)在数据库系统中,r

Python实现图片分割的多种方法总结

《Python实现图片分割的多种方法总结》图片分割是图像处理中的一个重要任务,它的目标是将图像划分为多个区域或者对象,本文为大家整理了一些常用的分割方法,大家可以根据需求自行选择... 目录1. 基于传统图像处理的分割方法(1) 使用固定阈值分割图片(2) 自适应阈值分割(3) 使用图像边缘检测分割(4)

Java中Switch Case多个条件处理方法举例

《Java中SwitchCase多个条件处理方法举例》Java中switch语句用于根据变量值执行不同代码块,适用于多个条件的处理,:本文主要介绍Java中SwitchCase多个条件处理的相... 目录前言基本语法处理多个条件示例1:合并相同代码的多个case示例2:通过字符串合并多个case进阶用法使用

C# foreach 循环中获取索引的实现方式

《C#foreach循环中获取索引的实现方式》:本文主要介绍C#foreach循环中获取索引的实现方式,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录一、手动维护索引变量二、LINQ Select + 元组解构三、扩展方法封装索引四、使用 for 循环替代

C# Where 泛型约束的实现

《C#Where泛型约束的实现》本文主要介绍了C#Where泛型约束的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录使用的对象约束分类where T : structwhere T : classwhere T : ne