在 C# 中,正则表达式是一种强大的模式匹配工具,它通过 System.Text.RegularExpressions 命名空间中的 Regex 类提供支持。量词在正则表达式中扮演着重要的角色,它们定义了一个模式应当出现的次数。本文将介绍 C# 中正则表达式的量词,并提供示例以帮助理解。
在正则表达式中,量词可以分为几类:
*:匹配前面的元素零次或多次。+:匹配前面的元素一次或多次。?:匹配前面的元素零次或一次。{n}:匹配前面的元素恰好 n 次。{n,}:匹配前面的元素至少 n 次。{n,m}:匹配前面的元素至少 n 次,但不超过 m 次。* 量词* 量词表示前面的元素可以出现零次或多次。
C#using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
string pattern = "bo*";
string input = "A ghost boooed at me and I bolted.";
foreach (Match match in Regex.Matches(input, pattern))
{
Console.WriteLine($"Found: {match.Value}");
}
}
}
输出:
C#Found: booo Found: bo

+ 量词+ 量词表示前面的元素至少出现一次。
C#using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
string pattern = "bo+";
string input = "A ghost boooed at me and I bolted.";
foreach (Match match in Regex.Matches(input, pattern))
{
Console.WriteLine($"Found: {match.Value}");
}
}
}
输出:
C#Found: booo Found: bo

? 量词? 量词表示前面的元素可以出现零次或一次。
C#using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
string pattern = "bo?";
string input = "A ghost booed at me and I bolted.";
foreach (Match match in Regex.Matches(input, pattern))
{
Console.WriteLine($"Found: {match.Value}");
}
}
}
输出:
C#Found: bo Found: bo

{n} 量词{n} 量词表示前面的元素必须恰好出现 n 次。
C#using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
string pattern = "bo{2}";
string input = "A ghost boooed at me and I bolted.";
foreach (Match match in Regex.Matches(input, pattern))
{
Console.WriteLine($"Found: {match.Value}");
}
}
}
输出:
C#Found: boo
{n,} 量词{n,} 量词表示前面的元素至少出现 n 次。
C#using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
string pattern = "bo{2,}";
string input = "A ghost boooed at me and I bolted.";
foreach (Match match in Regex.Matches(input, pattern))
{
Console.WriteLine($"Found: {match.Value}");
}
}
}
输出:
C#Found: booo

{n,m} 量词{n,m} 量词表示前面的元素至少出现 n 次,但不超过 m 次。
C#using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
string pattern = "bo{1,2}";
string input = "A ghost boooed at me and I bolted.";
foreach (Match match in Regex.Matches(input, pattern))
{
Console.WriteLine($"Found: {match.Value}");
}
}
}
输出:
C#Found: boo Found: bo

量词在正则表达式中是非常重要的,因为它们定义了模式的重复次数。在 C# 中,通过 Regex 类和量词的使用,你可以创建灵活且强大的模式匹配规则来处理字符串数据。理解并掌握不同的量词对于编写高效的正则表达式至关重要。通过上述示例,你应该能够开始在自己的 C# 项目中使用量词来进行模式匹配了。
本文作者:技术老小子
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!