Regex在c#中的用法
时间: 2023-11-25 20:05:56 浏览: 37
在C#中,可以使用System.Text.RegularExpressions命名空间来使用正则表达式。以下是Regex在C#中的一些用法示例:
1. 检查字符串是否匹配正则表达式:
```csharp
string pattern = @"^\d{4}-\d{2}-\d{2}$"; // 匹配日期格式 yyyy-MM-dd
string input = "2021-08-18";
bool isMatch = Regex.IsMatch(input, pattern);
```
2. 查找并替换字符串中的匹配项:
```csharp
string pattern = @"\b\d+\b"; // 匹配数字
string input = "There are 123 apples and 456 pears.";
string replacement = "999";
string result = Regex.Replace(input, pattern, replacement);
```
3. 使用捕获组提取字符串中的子串:
```csharp
string pattern = @"(\d{4})-(\d{2})-(\d{2})"; // 匹配日期格式 yyyy-MM-dd
string input = "Today is 2021-08-18.";
Match match = Regex.Match(input, pattern);
if (match.Success)
{
string year = match.Groups[1].Value;
string month = match.Groups[2].Value;
string day = match.Groups[3].Value;
Console.WriteLine("Year: " + year + ", Month: " + month + ", Day: " + day);
}
```
4. 使用正则表达式分割字符串:
```csharp
string pattern = @"\s+"; // 匹配空格
string input = "The quick brown fox jumps over the lazy dog.";
string[] substrings = Regex.Split(input, pattern);
foreach (string substring in substrings)
{
Console.WriteLine(substring);
}
```