C# 中的 Regex 类及其类方法是什么?
Regex 类用于表示正则表达式。正则表达式是一种可以与输入文本匹配的模式。
以下是 Regex 类的几种方法:
| 序号 | 方法及描述 |
|---|---|
| 1 | public bool IsMatch(string input) 指示 Regex 构造函数中指定的正则表达式是否在指定的输入字符串中找到匹配项。 |
| 2 | public bool IsMatch(string input, int startat) 指示 Regex 构造函数中指定的正则表达式是否在指定的输入字符串中找到匹配项,从字符串中的指定起始位置开始。 |
| 3 | public static bool IsMatch(string input, string pattern) 指示指定的正则表达式是否在指定的输入字符串中找到匹配项。 |
| 4 | public MatchCollection Matches(string input) 在指定的输入字符串中搜索正则表达式的所有出现。 |
| 5 | public string Replace(string input, string replacement) 在指定的输入字符串中,将与正则表达式模式匹配的所有字符串替换为指定的替换字符串。 |
| 6 | public string[] Split(string input) 根据 Regex 构造函数中指定的正则表达式模式定义的位置,将输入字符串拆分为子字符串数组。 |
以下示例使用 Matches() 方法搜索指定的输入字符串:
示例
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 = "make maze and manage to measure it";
Console.WriteLine("Matching words start with 'm' and ends with 'e':");
showMatch(str, @"\bm\S*e\b");
Console.ReadKey();
}
}
}输出
Matching words start with 'm' and ends with 'e': The Expression: \bm\S*e\b make maze manage measure
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP