一、正則表達式
是一種匹配輸入文本的模式,是由特殊字符組成,用于匹配字符串中的字符組合。
二、正則表達式有哪些?
1.Regex 類(引入System.Text.RegularExpressions;)
Regex 類用于表示一個正則表達式。
1)Regex.Match(inputString, "pattern");?? ?
返回第一個匹配項(即只找第一個)。
string input = "123abc456";
Match match = Regex.Match(input, @"\d+");if (match.Success)
{Console.WriteLine(match.Value); // 輸出: 123
}
2)Regex.Matches(...)?? ??? ??? ?
返回所有匹配項(全部找到)。
string input = "123abc456def789";
MatchCollection matches = Regex.Matches(input, @"\d+");foreach (Match match in matches)
{Console.WriteLine(match.Value); // 輸出: 123, 456, 789
}
3)Regex.IsMatch(...)?? ??? ??? ?
當你不需要具體匹配內容,只要知道是否“存在匹配”即可。
string input = "abc123xyz";
bool hasDigits = Regex.IsMatch(input, @"\d+");Console.WriteLine(hasDigits); // 輸出: True
4)Regex.Replace(...)?? ??? ??? ?
替換匹配到的內容為指定字符串。??
?eg1:
替換所有數字?? ?Regex.Replace(text, @"\d+", "*")
?eg2:
string input = "電話:123-456-7890,郵箱:test@example.com";// 替換所有數字為 *
string result1 = Regex.Replace(input, @"\d", "*");
Console.WriteLine(result1);
// 輸出:電話:***-***-****,郵箱:test@example.com// 替換所有郵箱地址為 [隱藏]
string result2 = Regex.Replace(input, @"\b[\w.-]+@[\w.-]+\.\w+\b", "[隱藏]");
Console.WriteLine(result2);
// 輸出:電話:123-456-7890,郵箱:[隱藏]
5)Regex.Split(...)?? ??? ??? ?
根據正則表達式匹配內容,將字符串分割成多個部分。
string input = "apple, banana; orange|grape";// 按照非單詞字符(逗號、分號、豎線)進行分割
string[] parts = Regex.Split(input, @"[,\s;|]+");foreach (string part in parts)
{Console.WriteLine(part);
}
// 輸出:
// apple
// banana
// orange
// grape
6.區別:
方法?? ?????????????????返回類型?? ?????????是否返回匹配內容?? ?是否修改原字符串?? ?主要用途
Match(...)?? ?????????Match?? ??????????????? 是(第一個)?? ?? 否?? ?????????獲取第一個匹配項
Matches(...)?? ?????MatchCollection?? 是(全部)?? ?????? 否?? ?????????獲取所有匹配項
IsMatch(...)?? ??????bool?? ?????????????????? 否? ? ? ? ? ? ? ? ? ? ? ? 否?? ?????????判斷是否匹配成功
Replace(...)?? ?????string?? ???????????????? 否? ? ? ? ? ? ? ? ? ? ? ?? 是?? ?????????替換匹配內容
Split(...)? ? ? ? ? ? ? string[]?? ?????????????? 否? ? ? ? ? ? ? ? ? ? ? ?? 是?? ?????????按匹配規則拆分字符串