Regex是對字串進行操作的一套功能強大的工具,下面簡要討論幾個問題.
1.Regex能做什麼?
簡單總結一下,有:測試判斷,尋找提取,刪除,替換字串的功能.
1)測試判斷:對於一個給定的字串,我們可以加以測試其是否滿足我們的特定字串的規則的要求.例如,輸入一個字串,我們要對它進行測試,判斷其是否是合法有效IP地址字串,以保證字串是我們需要的。
2)尋找提取:對於一個給定的字串,我們尋找出其中所有滿足規則的子字串.比如:我們要在一個字串中,尋找出所有的出現一個名字的位置,並提取滿足規則的子字串另加它用.
3)刪除:對於一個給定字串,我們要刪除其中符合規則的所有子字串,.如:我們要將一個字串中所有出現"abc"的子字串全刪除.
4)替換:對於一個給定字串,我們要替換其中符合規則的所有子字串.如:我們要將一個字串中所有出現"abc"的子字串全替換成"ABCDE".
2.我們如何使用Regex
這裡,我使用的是.NET類庫所提供的一個Regex類:System.Text.RegularExpressions.Regex
當然,也有很多其他的組件提供正則判斷引擎,只不過名稱或方法名有點不同,但是基礎的邏輯是一樣的.
關於Regex規則字串的寫法,可查詢相關資料文檔(本blog有相關內容,自行查閱.),我這裡只介紹如何使用Regex的一些簡單樣本.
3.一些樣本
1)測試判斷:使用Regex.IsMatch方法對字串加以測試判斷,看其是否是我們需要的特定格式的字串.
//這裡我使用一個IPRegex規則,能保證輸入的字串是IP地址字串.
using System;
using System.Text.RegularExpressions;
class App
{
static void Main()
{
//這是IPRegex規則字串(...由於是自己寫的,可能不夠精簡...)
string pattern = @"^([0-2]{0,1}[0-9]{0,1}[0-9]{1}\.){3}[0-2]{0,1}[0-9]{0,1}[0-9]{1}$";
//簡單編寫一些測試字串,如果有興趣,可以自己增加測試字串加以測試
string[] Inputs = { "255.255.255.0", "127.0.0.1", "djhfdj", "1272.2.2.1", "127.0.0.1a" };
foreach (string s in Inputs)
{
if (Regex.IsMatch(s, pattern)) //只需要這樣一個方法調用,就可以自動判斷出是否符合規則
Console.WriteLine(s+" 是正確的IP地址.");
else
Console.WriteLine(s + " 不是正確的IP地址.");
}
Console.Read();
}
}
2))尋找提取:使用Regex.Match或Regex.Matchs方法尋找並提取滿足規則的子字串
<1>//使用Regex.Match方法返回第一個滿足正則判斷規則的子字串
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
string pattern = @"abc";
//字串Input是你需要加以操作的目的字串
string Input = "fdkabcslabcd";
//使用Regex.Match方法,將從字串Input中尋找出第一個匹配pattern表達規則的子字串
//並返回一個Match對象,此Match對象的Index就是在Input字串中被找到的滿足規則的子字串索引位置,
//而Value屬性就是滿足規則的子字串的被複製的子字串
Match m = Regex.Match(Input, pattern);
if (m.Success) //判斷是否成功
{
Console.WriteLine("在原字串中的索引位置 "+m.Index + " 尋找的結果 " + m.Value); }
else
Console.WriteLine("沒有需要尋找的字串.");
Console.Read();
}
}
<2>使用Regex.Matchs方法返回所有滿足規則的子字串
using System;
using System.Text.RegularExpressions;
class App
{
static void Main()
{
string pattern = @"abc";
string Input = "dfkhabcfkdjabcek";
MatchCollection ms = Regex.Matches(Input, pattern);
foreach(Match m in ms)
{
Console.WriteLine("在原字串中的索引位置 " + m.Index + " 尋找的結果 " + m.Value);
}
Console.Read();
}
}
3)刪除:使用Regex.Replace方法,將尋找出來的子字串替換成"",其實就是刪除.
using System;
using System.Text.RegularExpressions;
class App
{
static void Main()
{
string pattern = @"abc";
string Input = "dfkhabcfkdjabcek";
string s = Regex.Replace(Input, pattern,"");
Console.WriteLine("刪除前:" + Input);
Console.WriteLine("刪除後:"+s);
Console.Read();
}
}
4)替換:使用Regex.Replace方法,將尋找出來的子字串替換成指定字串,就是替換啦
using System;
using System.Text.RegularExpressions;
class App
{
static void Main()
{
string pattern = @"abc";
string Input = "dfkhabcfkdjabcek";
//直接使用Replace方法指定需要替換的字串和要替換的字串
string s = Regex.Replace(Input, pattern,"|ABC|");
Console.WriteLine("替換前:" + Input);
Console.WriteLine("替換後:"+s);
Console.Read();
}
}