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 11

Found '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 11

Found '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,LINQ
                foreach (var word in from Match match in matches.Cast<Match>()//Cast强制显示转换
                                     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("没有重复的单词"); }
        }

        [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

 */

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/363565.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

DRV8301 踩坑记,Status1 D10 老是 Fault

波形如上&#xff1a; 看第一个时钟出来的数据&#xff08;Status1 读完自动清除&#xff1f;&#xff09;&#xff0c;因此数据是&#xff1a;0x20 输入结构体解析&#xff1a; 可以看到&#xff0c;FETHA_OC了也就是A桥上管过流了&#xff1b; 检查一下硬件看看&#xff1…

nodejs+vue+ElementUi高校创业项目申报系统w6f1g

此系统设计主要采用的是nodejs语言来进行开发&#xff0c;采用vue框架技术&#xff0c;框架分为三层&#xff0c;分别是控制层Controller&#xff0c;业务处理层Service&#xff0c;持久层dao&#xff0c;能够采用多层次管理开发&#xff0c;对于各个模块设计制作有一定的安全性…

Lazysysadmin

信息收集 # nmap -sn 192.168.1.0/24 -oN live.port Starting Nmap 7.94 ( https://nmap.org ) at 2024-01-30 21:10 CST Nmap scan report for 192.168.1.1 (192.168.1.1) Host is up (0.00075s latency). MAC Address: 00:50:56:C0:00:08 (VMware) Nma…

强化学习-google football 实验记录

google football 实验记录 1. gru模型和dense模型对比实验 实验场景&#xff1a;5v5(控制蓝方一名激活球员)&#xff0c;跳4帧&#xff0c;即每个动作执行4次 实验点&#xff1a; 修复dense奖励后智能体训练效果能否符合预期 实验目的&#xff1a; 对比gru 长度为16 和 dens…

机器学习算法决策树

决策树的介绍 决策树是一种常见的分类模型&#xff0c;在金融风控、医疗辅助诊断等诸多行业具有较为广泛的应用。决策树的核心思想是基于树结构对数据进行划分&#xff0c;这种思想是人类处理问题时的本能方法。例如在婚恋市场中&#xff0c;女方通常会先询问男方是否有房产&a…

Outlook技巧:如何插入可以用指定浏览器打开的链接

Outlook中的链接&#xff0c;有时直接点击无法打开&#xff0c;找本地Edge才能打开。如何让Url能够指定打开的浏览器呢&#xff1f; 插入链接时&#xff0c;直接加上前缀Microsoft-edge即可。 操作步骤&#xff1a; 编辑邮件界面&#xff0c;菜单选择插入-》链接 在链接地址…

如何使用淘宝客?

1.定义&#xff1a;是一种按成交计费的推广工具&#xff0c;由淘宝客帮助商家推广商品&#xff0c;买家通过推广链接进入完成交易后&#xff0c;商家按照设置佣金支付给淘宝客费用。 2.优势&#xff1a; &#xff08;1&#xff09;展示、点击全免费。 &#xff08;2&#xf…

Redis核心技术与实战【学习笔记】 - 10.浅谈CPU架构对Redis性能的影响

概述 可能很多人都认为 Redis 和 CPU 的关系简单&#xff0c;Redis 的线程在 CPU 上运行&#xff0c;CPU 快 Reids 处理请求的速度也很快。 其实&#xff0c;这种认知是片面的&#xff0c;CPU 的多核架构及多 CPU 结构&#xff0c;也会影响到 Redis 的性能。如果不了解 CPU 对…

嵌入式学习第十五天

内存管理: 1.malloc void *malloc(size_t size); 功能: 申请堆区空间 参数: size:申请堆区空间的大小 返回值: 返回获得的空间的首地址 失败返回NULL 2.free void free(void *ptr); 功能: 释放堆区空间 注…

【芯片设计- RTL 数字逻辑设计入门 番外篇 8.1 -- memory repair 详细介绍】

文章目录 memory repair 详细介绍Memory Repair 方法Memory Repair 过程举例memory repair 详细介绍 SoC (System on Chip) 的 Memory Repair 是一种技术,用于检测和修复内存中的损坏单元。由于SoC内部集成了大量的逻辑和存储单元,包括RAM(随机访问存储器)、ROM(只读存储…

使用 vite 配置请求代理

介绍vite vue官方提供的前端构建工具。 由两个部分组成 开发服务器&#xff1a;基于ES模块提供丰富的内建功能 构建指令&#xff1a;使用 Rollup 打包代码&#xff0c;提供预设配置 Rollup&#xff1a; Rollup 是一个 JavaScript 模块打包器&#xff0c;它可以将多个模块打包成…

UG949 适用于 FPGA 和 SoC 的UltraFast 设计方法指南

使用RTL创建设计 定义RTL设计层级 模块边界输出进行寄存 即寄存器输出&#xff0c;打一拍 IP的使用 AMBA AXI

BPF 管理器 bpfman 简介

1. 背景 Fedora 40 提案建议将 bpfman 作为默认的程序管理器 &#xff0c;开源项目 bpfman 可以实现对 eBPF 运行状态的深入了解&#xff0c;从而实现更轻松地管理 eBPF 程序&#xff08;包括加载、卸载、运行状态查看等&#xff09;。该提案还需要 Fedora 工程和指导委员会 (…

AIGC专题:从0到1精益创新 AIGC产品应用及商业化落地实践

今天分享的是AIGC系列深度研究报告&#xff1a;《AIGC专题&#xff1a;从0到1精益创新 AIGC产品应用及商业化落地实践》。 &#xff08;报告出品方&#xff1a;易点天下&#xff09; 报告共计&#xff1a;38页 企业内部增效-AI知识库 企业内部IT、运维、人力资源、行政等等日…

Unity 模板方法模式(实例详解)

文章目录 简介示例1&#xff1a;游戏关卡流程示例2&#xff1a;测试试卷类示例3&#xff1a;游戏场景构建流程示例4&#xff1a;游戏动画序列示例5&#xff1a;游戏对象初始化过程 简介 Unity中的模板方法模式是一种行为设计模式&#xff0c;它在父类中定义了一个算法的框架&a…

微软新的内部开发部门发现了第一个 Windows 12 版本

Windows 11 被证明让很多人有点失望&#xff0c;很多 Windows 10 用户认为没有理由升级。 这意味着有大量用户渴望一些大而令人印象深刻的东西——而这正是 Windows 12 所希望的。 无论您是 Windows 10 的忠实拥趸&#xff0c;还是渴望更新、更闪亮的 Windows 11 采用者&#x…

笔记本电脑Win11重装系统教程

在笔记本电脑Win11操作过程中&#xff0c;用户如果遇到很严重的系统问题&#xff0c;就可以重新正常的Win11系统&#xff0c;快速解决Win11系统问题。但是&#xff0c;部分新手用户不知道不知道如何操作才能给Win11笔记本电脑重装系统&#xff1f;以下小编分享笔记本电脑Win11重…

分布式事务(五)——基于本地消息和可靠消息的解决方案

系列目录&#xff1a; 《分布式事务&#xff08;一&#xff09;—— 事务的基本概念》 《分布式事务&#xff08;二&#xff09;—— CAP和Base理论》 《分布式事务&#xff08;三&#xff09;—— 两阶段提交解决方案&#xff08;2PC&#xff09;》 《分布式事务&#xff0…

安卓滚动视图ScrollView

<?xml version"1.0" encoding"utf-8"?> <LinearLayout xmlns:android"http://schemas.android.com/apk/res/android"android:layout_width"match_parent"android:layout_height"match_parent"android:orientatio…

mybatisplus-多数据源配置

1. 流程 pom文件yml配置多数据源具体服务添加注解DS(“***”) 1.pom文件 <!--mybatis plus 起步依赖--><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.4.0</vers…
最新文章