正則表達式是匹配輸入文本的模式。.Net框架提供了允許這種匹配的正則表達式引擎。模式由一個或多個字符文字,運算符或構(gòu)造組成。
有各種類型的字符,運算符和結(jié)構(gòu),可以讓您用來定義正則表達式。點擊以下鏈接查找這些結(jié)構(gòu)。
正則表達式 - Regex
類用于表示正則表達式。 它有以下常用的方法:
序號 | 方法 | 描述 |
---|---|---|
1 | public bool IsMatch(string input) | 指示在正則表達式構(gòu)造函數(shù)中指定的正則表達式是否在指定的輸入字符串中找到匹配項。 |
2 | public bool IsMatch(string input, int startat) | 指示在正則表達式構(gòu)造函數(shù)中指定的正則表達式是否在指定的輸入字符串(input )中找到匹配,從字符串中指定的起始(startat )位置開始。 |
3 | public static bool IsMatch(string input, string pattern) | 在指定的正則表達式是否在指定的輸入字符串中找到匹配項。 |
4 | public MatchCollection Matches(string input) | 搜索所有出現(xiàn)正則表達式的指定輸入字符串。 |
5 | public string Replace(string input, string replacement) | 在指定的輸入字符串中,將與正則表達式模式匹配的所有字符串替換為指定的替換字符串(replacementreplacement )。 |
6 | public string[] Split(string input) | 將輸入字符串拆分為由正則表達式構(gòu)造函數(shù)中指定的正則表達式模式定義的位置的子字符串數(shù)組。 |
有關(guān)方法和屬性的完整列表,請閱讀Microsoft C# 文檔。
以下示例匹配以“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();
}
}
}
當編譯和執(zhí)行上述代碼時,會產(chǎn)生以下結(jié)果:
Matching words that start with 'S':
The Expression: \bS\S*
Splendid
Suns
以下示例匹配以'm'
開頭并以'e'
結(jié)尾的單詞:
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();
}
}
}
當編譯和執(zhí)行上述代碼時,會產(chǎn)生以下結(jié)果:
Matching words start with 'm' and ends with 'e':
The Expression: \bm\S*e\b
make
maze
manage
measure
此示例替換了額外多余的空格:
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();
}
}
}
當編譯和執(zhí)行上述代碼時,會產(chǎn)生以下結(jié)果:
Original String: Hello World
Replacement String: Hello World