首页 > 编程语言 >C#下使用正则表达式

C#下使用正则表达式

时间:2024-04-23 23:14:23浏览次数:24  
标签:字符 匹配 string C# private 正则表达式 static 使用 Console

常用元字符

字符 描述
\ 将下一个字符标记为一个特殊字符、或一个原义字符、或一个 向后引用、或一个八进制转义符。例如,'n' 匹配字符 "n"。'\n' 匹配一个换行符。序列 '\\' 匹配 "\" 而 "\(" 则匹配 "("。
^ 匹配输入字符串的开始位置。如果设置了 RegExp 对象的 Multiline 属性,^ 也匹配 ''\n' 或 '\r' 之后的位置。
$ 匹配输入字符串的结束位置。如果设置了RegExp 对象的 Multiline 属性,$ 也匹配 '\n' 或 '\r' 之前的位置。
* 匹配前面的子表达式零次或多次。例如,zo* 能匹配 "z" 以及 "zoo"或者"zooooo"等等。* 等价于{0,}。
+ 匹配前面的子表达式一次或多次。例如,'zo+' 能匹配 "zo" 以及 "zoo"等等,但不能匹配 "z"。+ 等价于 {1,}。
? 匹配前面的子表达式零次或一次。例如,"do(es)?" 可以匹配 "do" 或 "does" 。? 等价于 {0,1}。
{n} n 是一个非负整数。匹配确定的 n 次。例如,'o{2}' 不能匹配 "Bob" 中的 'o',但是能匹配 "food" 中的两个 o。
{n,} n 是一个非负整数。至少匹配n 次。例如,'o{2,}' 不能匹配 "Bob" 中的 'o',但能匹配 "foooood" 中的所有 o。'o{1,}' 等价于 'o+'。'o{0,}' 则等价于 'o*'。
{n,m} m 和 n 均为非负整数,其中n <= m。最少匹配 n 次且最多匹配 m 次。例如,"o{1,3}" 将匹配 "fooooood" 中的前三个 o。'o{0,1}' 等价于 'o?'。请注意在逗号和两个数之间不能有空格。
? 当该字符紧跟在任何一个其他限制符 (*, +, ?, {n}, {n,}, {n,m}) 后面时,匹配模式是非贪婪的。非贪婪模式尽可能少的匹配所搜索的字符串,而默认的贪婪模式则尽可能多的匹配所搜索的字符串。例如,对于字符串 "oooo",'o+?' 将匹配单个 "o",而 'o+' 将匹配所有 'o'。再例如对于字符串"ABCDEAB","(AB)*?"匹配到的结果是"AB"而不是"ABCDEAB"
. 匹配除换行符(\n、\r)之外的任何单个字符。要匹配包括 '\n' 在内的任何字符,请使用像`"(.
(pattern) 匹配 pattern 并获取这一匹配。所获取的匹配可以从产生的 Matches 集合得到,在VBScript 中使用 SubMatches 集合,在JScript 中则使用 0…0…0…9 属性。要匹配圆括号字符,请使用 '(' 或 ')'。
(?:pattern) 匹配 pattern 但不获取匹配结果,也就是说这是一个非获取匹配,不进行存储供以后使用。这在使用 "或" 字符 (`
(?=pattern) 正向肯定预查(look ahead positive assert),在任何匹配pattern的字符串开始处匹配查找字符串。这是一个非获取匹配,也就是说,该匹配不需要获取供以后使用。例如,`"Windows(?=95
(?!pattern) 正向否定预查(negative assert),在任何不匹配pattern的字符串开始处匹配查找字符串。这是一个非获取匹配,也就是说,该匹配不需要获取供以后使用。例如`"Windows(?!95
(?<=pattern) 反向(look behind)肯定预查,与正向肯定预查类似,只是方向相反。例如,"`(<=95
(?<!pattern) 反向否定预查,与正向否定预查类似,只是方向相反。例如"`(?<!95
x | y 匹配 x 或 y。例如,'z|food' 能匹配 "z" 或 "food"。'(z`
[xyz] 字符集合。匹配所包含的任意一个字符。例如, '[abc]' 可以匹配 "plain" 中的 'a'。
[^xyz] 负值字符集合。匹配未包含的任意字符。例如, '[^abc]' 可以匹配 "plain" 中的'p'、'l'、'i'、'n'。
[a-z] 字符范围。匹配指定范围内的任意字符。例如,'[a-z]' 可以匹配 'a' 到 'z' 范围内的任意小写字母字符。
[^a-z] 负值字符范围。匹配任何不在指定范围内的任意字符。例如,'[^a-z]' 可以匹配任何不在 'a' 到 'z' 范围内的任意字符。
\b 匹配一个单词边界,也就是指单词和空格间的位置。例如, 'er\b' 可以匹配"never" 中的 'er',但不能匹配 "verb" 中的 'er'。
\B 匹配非单词边界。'er\B' 能匹配 "verb" 中的 'er',但不能匹配 "never" 中的 'er'。
\cx 匹配由 x 指明的控制字符。例如, \cM 匹配一个 Control-M 或回车符。x 的值必须为 A-Z 或 a-z 之一。否则,将 c 视为一个原义的 'c' 字符。
\d 匹配一个数字字符。等价于[0-9]
\D 匹配一个非数字字符。等价于 [^0-9]
\f 匹配一个换页符。等价于 \x0c 和 \cL。
\n 匹配一个换行符。等价于 \x0a 和 \cJ。
\r 匹配一个回车符。等价于 \x0d 和 \cM。
\s 匹配任何空白字符,包括空格、制表符、换页符等等。等价于 [\f\n\r\t\v]
\S 匹配任何非空白字符。等价于 [^ \f\n\r\t\v]
\t 匹配一个制表符。等价于 \x09 和 \cI。
\v 匹配一个垂直制表符。等价于 \x0b 和 \cK。
\w 匹配字母、数字、下划线。等价于'[A-Za-z0-9_]'
\W 匹配非字母、数字、下划线。等价于 '[^A-Za-z0-9_]'
\xn 匹配 n,其中 n 为十六进制转义值。十六进制转义值必须为确定的两个数字长。例如,'\x41' 匹配 "A"。'\x041' 则等价于 '\x04' & "1"。正则表达式中可以使用 ASCII 编码。
\num 匹配 num,其中 num 是一个正整数。对所获取的匹配的引用。例如,'(.)\1' 匹配两个连续的相同字符。
\n 标识一个八进制转义值或一个向后引用。如果 \n 之前至少 n 个获取的子表达式,则 n 为向后引用。否则,如果 n 为八进制数字 (0-7),则 n 为一个八进制转义值。
\nm 标识一个八进制转义值或一个向后引用。如果 \nm 之前至少有 nm 个获得子表达式,则 nm 为向后引用。如果 \nm 之前至少有 n 个获取,则 n 为一个后跟文字 m 的向后引用。如果前面的条件都不满足,若 n 和 m 均为八进制数字 (0-7),则 \nm 将匹配八进制转义值 nm。
\nml 如果 n 为八进制数字 (0-3),且 m 和 l 均为八进制数字 (0-7),则匹配八进制转义值 nml。
\un 匹配 n,其中 n 是一个用四个十六进制数字表示的 Unicode 字符。例如, \u00A9 匹配版权符号 (?)。

C#下使用如下

Regex.Match          获取单个或第一个匹配项
Regex.Matches        获取全部匹配项返回MatchCollection
Regex.Replace        将字符串替换成其他字符串

例子1

using System.Text.RegularExpressions;

namespace TestAll
{
    public class Program
    {
        private static readonly string Target = "New Challenges are Live!";

        private static readonly string MatchText = @"\S*";


        private static void Main(string[] args)
        {
            var result = Regex.Match(Target, MatchText, RegexOptions.IgnoreCase);
            Console.WriteLine($"{result.Value}");
            Console.ReadLine();
        }
    }
}

运行效果如下:

例子2

C# 匹配多个结果

using System.Text.RegularExpressions;

namespace TestAll
{
    public class Program
    {
        //文本内容
        private static readonly string Target = @"The Dispose Pattern in C# is all about the mechanics of effectively disposing of your instance fields
                    that implement IDisposable and freeing up the unmanaged resources that you directly hold in your class.
                    I’d like to shed some light on many of the uncertainties when it comes to writing explicit teardown code for releasing your resources.
                    This is not a complete beginner introduction to IDisposable and garbage collection in .Net.
                    However, some very basic knowledge should be sufficient to follow along as I’ll also give many explanations and definitions along the way.
                    This post is a step by step guide for implementing the full-blown Dispose Pattern.
                    It starts simple with a sealed class with a single IDisposable instance field.
                    Then I gradually increase the complexity by creating additional scenarios like adding an unmanaged resource and introducing inheritance.";

        //匹配的正则表达式
        private static readonly string MatchText = @"th\S*";

        private static void Main(string[] args)
        {
            var result = Regex.Matches(Target, MatchText, RegexOptions.IgnoreCase);
            for (int i = 0; i < result.Count; i++)
            {
                Console.WriteLine($"结果{i + 1}:");
                Console.WriteLine(result[i].Value);
            }
            Console.ReadLine();
        }
    }
}

运行效果如下

例子3

提取两个"the"字符串之间的文本内容,贪婪匹配的模式即最宽的字符串

using System.Text.RegularExpressions;

namespace TestAll
{
    public class Program
    {
        //文本内容
        private static readonly string Target = @"The Dispose Pattern in C# is all about the mechanics of effectively disposing of your instance fields
                    that implement IDisposable and freeing up the unmanaged resources that you directly hold in your class.
                    I’d like to shed some light on many of the uncertainties when it comes to writing explicit teardown code for releasing your resources.
                    This is not a complete beginner introduction to IDisposable and garbage collection in .Net.
                    However, some very basic knowledge should be sufficient to follow along as I’ll also give many explanations and definitions along the way.
                    This post is a step by step guide for implementing the full-blown Dispose Pattern.
                    It starts simple with a sealed class with a single IDisposable instance field.
                    Then I gradually increase the complexity by creating additional scenarios like adding an unmanaged resource and introducing inheritance.";

        //匹配的正则表达式
        private static readonly string MatchText = @"the[\s\S]*the";

        private static void Main(string[] args)
        {
            var result = Regex.Matches(Target, MatchText, RegexOptions.IgnoreCase);
            for (int i = 0; i < result.Count; i++)
            {
                Console.WriteLine($"结果{i + 1}:");
                Console.WriteLine(result[i].Value);
            }
            Console.ReadLine();
        }
    }
}

运行效果如下

例子4

提取两个"the"字符串之间的文本内容,懒惰匹配的模式即最窄的字符串

using System.Text.RegularExpressions;

namespace TestAll
{
    public class Program
    {
        //文本内容
        private static readonly string Target = @"The Dispose Pattern in C# is all about the mechanics of effectively disposing of your instance fields
                    that implement IDisposable and freeing up the unmanaged resources that you directly hold in your class.
                    I’d like to shed some light on many of the uncertainties when it comes to writing explicit teardown code for releasing your resources.
                    This is not a complete beginner introduction to IDisposable and garbage collection in .Net.
                    However, some very basic knowledge should be sufficient to follow along as I’ll also give many explanations and definitions along the way.
                    This post is a step by step guide for implementing the full-blown Dispose Pattern.
                    It starts simple with a sealed class with a single IDisposable instance field.
                    Then I gradually increase the complexity by creating additional scenarios like adding an unmanaged resource and introducing inheritance.";

        //匹配的正则表达式
        private static readonly string MatchText = @"the[\s\S]*?the";

        private static void Main(string[] args)
        {
            var result = Regex.Matches(Target, MatchText, RegexOptions.IgnoreCase);
            for (int i = 0; i < result.Count; i++)
            {
                Console.WriteLine($"结果{i + 1}:");
                Console.WriteLine(result[i].Value);
            }
            Console.ReadLine();
        }
    }
}

运行结果如下

例子5

将字符串"the"替换成"Hello"

using System.Text.RegularExpressions;

namespace TestAll
{
    public class Program
    {
        //文本内容
        private static readonly string Target = @"The Dispose Pattern in C# is all about the mechanics of effectively disposing of your instance fields
                    that implement IDisposable and freeing up the unmanaged resources that you directly hold in your class.
                    I’d like to shed some light on many of the uncertainties when it comes to writing explicit teardown code for releasing your resources.
                    This is not a complete beginner introduction to IDisposable and garbage collection in .Net.
                    However, some very basic knowledge should be sufficient to follow along as I’ll also give many explanations and definitions along the way.
                    This post is a step by step guide for implementing the full-blown Dispose Pattern.
                    It starts simple with a sealed class with a single IDisposable instance field.
                    Then I gradually increase the complexity by creating additional scenarios like adding an unmanaged resource and introducing inheritance.";

        //匹配的正则表达式
        private static readonly string MatchText = @"the";

        private static void Main(string[] args)
        {
            var resul = Regex.Replace(Target, MatchText, "Hello");
            Console.WriteLine(resul);
            Console.ReadLine();
        }
    }
}

运行效果如下

标签:字符,匹配,string,C#,private,正则表达式,static,使用,Console
From: https://www.cnblogs.com/SmallCarp/p/18154026

相关文章

  • PostScript 是一种页面描述语言,最初由 Adobe 公司开发。它被设计用于描述页面的外观和
    PostScript的起源可以追溯到1982年,当时由Adobe公司的创始人之一约翰·沃诺克(JohnWarnock)和查尔斯·格什克(CharlesGeschke)共同开发。沃诺克和格什克当时都是在施乐帕克研究中心工作,他们在那里开始了对一种新的页面描述语言的研究和开发。当时的打印技术面临着一些挑战,......
  • ECMAScript(简称 ES)是一种由 Ecma 国际组织制定的脚本语言标准,用于定义脚本语言的语法
    ECMAScript(简称ES)是一种由Ecma国际组织制定的脚本语言标准,用于定义脚本语言的语法、类型、语义和其他核心特性。它的设计初衷是为了使不同的浏览器和开发者能够使用一致的语法和特性开发Web应用程序,从而提高跨平台和跨浏览器的互操作性。ECMAScript标准的制定由Ecma......
  • 挑战前端基础120题--JavaScript 中如何实现链式调用的函数?
    一.何为链式调用?链式调用是一种简化过程的编码方式,使代码看起来更加简洁~它允许你通过在方法调用之间返回对象本身,从而连续地调用多个方法;比较常见的链式调用:jQuery,Promise等,通过多次书写.或()操作来调用。二.实现的原理?每次执行完成后返回自己/新的自己,这样可以确保后续的......
  • 6-1 使用函数求特殊a串数列和
    给定两个均不超过9的正整数a和n,要求编写函数fn(a,n)求a+aa+aaa++⋯+aa⋯aa(n个a)之和,fn须返回的是数列和函数接口定义: fn(a,n)其中a和n都是用户传入的参数。a的值在[1,9]范围;n是[1,9]区间内的个位数。函数须返回级数和裁判测试程序样例: /*请在这里填写答......
  • 6-2 使用函数求余弦函数的近似值
    本题要求实现一个函数,用下列公式求cos(x)近似值,精确到最后一项的绝对值小于eps(绝对值小于eps的项不要加):cos(x)=0!x0​−2!x2​+4!x4​−6!x6​+...函数接口定义:funcos(eps,x),其中用户传入的参数为eps和x;函数funcos应返回用给定公式计算出来,保留小数4位。函数接口定义: 函......
  • 【VMware by Broadcom】产品版本和内部版本号
    VMwareESXi/ESXBuildnumbersandversionsofVMwareESXi/ESX(2143832)VMwarevCenterServerBuildnumbersandversionsofVMwarevCenterServer(2143838)VMwarevCenterChargebackBuildnumbersandversionsofVMwarevCenterChargeback (2143841)V......
  • heackmyvmRegistry
    heackmyvmRegistryprogrambamuwe@bamuwe:~$checksecprogram[*]'/program'Arch:amd64-64-littleRELRO:PartialRELROStack:NocanaryfoundNX:NXunknown-GNU_STACKmissingPIE:NoPIE(0x400000)S......
  • [BJDCTF 2020]YDSneedGirlfriend
    [BJDCTF2020]YDSneedGirlfriendUAF|所谓UAF漏洞是指程序在运行时通过悬空指针(悬空指针是指仍然指向已被释放内存空间的指针)访问已经被释放的内存.bamuwe@bamuwe:~/YDSneedGirlfriend$lddgirlfriendlinux-vdso.so.1(0x00007ffd09fec000)/home/bamuwe/pw......
  • R语言随机森林RandomForest、逻辑回归Logisitc预测心脏病数据和可视化分析|附代码数据
    全文链接:http://tecdat.cn/?p=22596最近我们被客户要求撰写关于预测心脏病的研究报告,包括一些图形和统计输出。本报告是对心脏研究的机器学习/数据科学调查分析。更具体地说,我们的目标是在心脏研究的数据集上建立一些预测模型,并建立探索性和建模方法。但什么是心脏研究?研究大纲......
  • 把CIFAR-10数据集分类保存成图片
    一:cifar10数据集简介CIFAR-10数据集是一个广泛用于计算机视觉领域的数据集,主要用于图像分类任务。该数据集由Hinton的学生AlexKrizhevsky和IlyaSutskever整理得到。它包含10个不同类别的RGB彩色图片,每个图片的尺寸为32×32像素。这10个类别分别是飞机(airplane)、汽车(automobil......