正则表达式是匹配输入文本的模式。.Net框架提供了允许这种匹配的正则表达式引擎。模式由一个或多个字符文字,运算符或构造组成。
定义正则表达式的构造
有各种类型的字符,运算符和结构,可以让您用来定义正则表达式。点击以下链接查找这些结构。
Regex类
正则表达式 - Regex
类用于表示正则表达式。 它有以下常用的方法:
序号 | 方法 | 描述 |
---|---|---|
1 | public bool IsMatch(string input) | 指示在正则表达式构造函数中指定的正则表达式是否在指定的输入字符串中找到匹配项。 |
2 | public bool IsMatch(string input, int startat) | 指示在正则表达式构造函数中指定的正则表达式是否在指定的输入字符串(input )中找到匹配,从字符串中指定的起始(startat )位置开始。 |
3 | public static bool IsMatch(string input, string pattern) | 在指定的正则表达式是否在指定的输入字符串中找到匹配项。 |
4 | public MatchCollection Matches(string input) | 搜索所有出现正则表达式的指定输入字符串。 |
5 | public string Replace(string input, string replacement) | 在指定的输入字符串中,将与正则表达式模式匹配的所有字符串替换为指定的替换字符串(replacementreplacement )。 |
6 | public string[] Split(string input) | 将输入字符串拆分为由正则表达式构造函数中指定的正则表达式模式定义的位置的子字符串数组。 |
有关方法和属性的完整列表,请阅读Microsoft C# 文档。
实例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 &aposS&apos: ")
showMatch(str, @"\bS\S*")
Console.ReadKey()
}
}
}
当编译和执行上述代码时,会产生以下结果:
Matching words that start with &aposS&apos:
The Expression: \bS\S*
Splendid
Suns
示例2
以下示例匹配以&aposm&apos
开头并以&apose&apos
结尾的单词:
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 &aposm&apos and ends with &apose&apos:")
showMatch(str, @"\bm\S*e\b")
Console.ReadKey()
}
}
}
当编译和执行上述代码时,会产生以下结果:
Matching words start with &aposm&apos and ends with &apose&apos:
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)
Console.WriteLine("Replacement String: {0}", result)
Console.ReadKey()
}
}
}
当编译和执行上述代码时,会产生以下结果:
Original String: Hello World
Replacement String: Hello World