亿迅智能制造网
工业4.0先进制造技术信息网站!
首页 | 制造技术 | 制造设备 | 工业物联网 | 工业材料 | 设备保养维修 | 工业编程 |
home  MfgRobots >> 亿迅智能制造网 >  >> Industrial programming >> C语言

C# 正则表达式完全指南:Regex 类、常用模式与实战示例

正则表达式是可匹配输入文本的模式。.NET 框架提供正则表达式引擎执行匹配。模式由字符字面量、运算符、构造组成。

正则表达式构造分类

Regex 类常用方法

序号方法及说明
1IsMatch(input):指示正则是否在输入字符串中找到匹配
2IsMatch(input, startat):从指定位置开始匹配
3IsMatch(input, pattern):静态方法,指定模式匹配
4Matches(input):搜索所有匹配项,返回 MatchCollection
5Replace(input, replacement):替换所有匹配项
6Split(input):按正则模式拆分字符串数组

实战示例

示例 1:匹配以 'S' 开头的单词

using System;
using System.Text.RegularExpressions;
namespace RegExApplication {
    class Program {
        private static void showMatch(string text, string expr) {
            Console.WriteLine("The Expression: " + expr);
            MatchCollection mc = Regex.Matches(text, expr);
            foreach (Match m in mc) Console.WriteLine(m);
        }
        
        static void Main(string[] args) {
            string str = "A Thousand Splendid Suns";
            Console.WriteLine("Matching words that start with 'S': ");
            showMatch(str, @"\bS\S*");
            Console.ReadKey();
        }
    }
}

输出:

Matching words that start with 'S':
The Expression: \bS\S*
Splendid
Suns

示例 2:匹配以 'm' 开头 'e' 结尾的单词

string str = "make maze and manage to measure it";
showMatch(str, @"\bm\S*e\b");

输出:

Matching words start with 'm' and ends with 'e':
The Expression: \bm\S*e\b
make
maze
manage
measure

示例 3:替换多余空白字符

using System;
using System.Text.RegularExpressions;
namespace RegExApplication {
    class Program {
        static void Main(string[] args) {
            string input = "Hello    World ";
            string pattern = @"\s+";
            string replacement = " ";
            Regex rgx = new Regex(pattern);
            string result = rgx.Replace(input, replacement);
            Console.WriteLine("Original String: {0}", input);      // Hello    World 
            Console.WriteLine("Replacement String: {0}", result);  // Hello World
            Console.ReadKey();
        }
    }
}

常用正则模式速查

模式说明示例匹配
\d数字0-9
\D非数字a, #
\w单词字符a, Z, 0, _
\W非单词字符@, 空格
\s空白字符空格, \t, \n
\S非空白字符a, 1
.任意字符(除换行)a, 1, @
^字符串开始
$字符串结束
\b单词边界
*0 次或多次
+1 次或多次
?0 次或 1 次
{n}恰好 n 次
{n,}至少 n 次
{n,m}n 到 m 次
(...)捕获组
(?:...)非捕获组
|或

常用验证正则

性能与最佳实践

C语言

  1. C# 表达式、语句与代码块:全面指南与实战示例
  2. 掌握 C# 字符串:基础、操作与进阶技巧完全指南
  3. C++ 字符串函数实战:strcpy、strcat、strlen、strcmp 详解与示例
  4. C 语言字符串完全指南:声明、输入输出与库函数详解
  5. Python str.count() 完全指南:统计字符与子串出现次数实战
  6. 理解 Java 表达式、语句与代码块
  7. 精通 Java 字符串:创建、方法与最佳实践
  8. 精通 Java 枚举字符串表示:默认行为、toString 重写与进阶模式
  9. 掌握 Java Lambda 表达式:从基础到 Stream API 实战
  10. Java Strings 类:掌握字符串创建与操作
  11. Java 正则表达式完全指南:掌握 java.util.regex 模式匹配
  12. Java 8 概览:函数式编程、流式 API 与日期时间新特性