可以使用两个主要策略在字符串中搜索文本。 String类搜索特定文本的方法。 正则表达式搜索文本中的模式。
字符串类型是类的System.String别名,提供了许多有用的方法来搜索字符串的内容。 其中包括Contains,,StartsWith,EndsWith,IndexOf。 LastIndexOf 该 System.Text.RegularExpressions.Regex 类提供了丰富的词汇来搜索文本中的模式。 在本文中,你将了解这些技术和如何根据需要选择最佳方法。
字符串是否包含文本?
String.Contains和String.StartsWithString.EndsWith方法在字符串中搜索特定文本。 以下示例显示了每种方法以及使用不区分大小写的搜索的变体:
string factMessage = "Extension methods have all the capabilities of regular static methods.";
// Write the string and include the quotation marks.
Console.WriteLine($"\"{factMessage}\"");
// Simple comparisons are always case sensitive!
bool containsSearchResult = factMessage.Contains("extension");
// Raw string literals can work here because the output doesn't begin with "
Console.WriteLine($"""Contains "extension"? {containsSearchResult}""");
// For user input and strings that will be displayed to the end user,
// use the StringComparison parameter on methods that have it to specify how to match strings.
bool ignoreCaseSearchResult = factMessage.StartsWith("extension", System.StringComparison.CurrentCultureIgnoreCase);
Console.WriteLine($"""Starts with "extension"? {ignoreCaseSearchResult} (ignoring case)""");
bool endsWithSearchResult = factMessage.EndsWith(".", System.StringComparison.CurrentCultureIgnoreCase);
Console.WriteLine($"Ends with '.'? {endsWithSearchResult}");
前面的示例演示了使用这些方法的重要要点。 默认情况下,搜索区分大小写。 使用 StringComparison.CurrentCultureIgnoreCase 枚举值指定不区分大小写的搜索。
在字符串中,所寻求的文本在什么位置出现?
这些 IndexOf 和 LastIndexOf 方法还会在字符串中搜索文本。 这些方法返回所寻求文本的位置。 如果未找到文本,则返回 -1。 以下示例显示搜索单词“methods”的第一个和最后一个匹配项,并显示两者之间的文本。
string factMessage = "Extension methods have all the capabilities of regular static methods.";
// Write the string and include the quotation marks.
Console.WriteLine($"\"{factMessage}\"");
// This search returns the substring between two strings, so
// the first index is moved to the character just after the first string.
int first = factMessage.IndexOf("methods") + "methods".Length;
int last = factMessage.LastIndexOf("methods");
string str2 = factMessage.Substring(first, last - first);
Console.WriteLine($"""Substring between "methods" and "methods": '{str2}'""");
使用正则表达式查找特定文本
该 System.Text.RegularExpressions.Regex 类可用于搜索字符串。 这些搜索可能很复杂,从简单到复杂的文本模式。
下面的代码示例在句子中搜索单词“the”或“their”,忽略大小写。 静态方法 Regex.IsMatch 执行搜索。 为它提供要搜索的字符串和搜索模式。 在这种情况下,第三个参数指定不区分大小写的搜索。 有关详细信息,请参阅 System.Text.RegularExpressions.RegexOptions。
搜索模式描述搜索的文本。 下表描述了搜索模式的每个元素。 (下表使用单个\,在 C# 字符串中必须转义为\\)。
| 图案 | Meaning |
|---|---|
the |
匹配文本“the”字符 |
(eir)? |
匹配“eir”出现0或1次 |
\s |
匹配空白字符 |
string[] sentences =
[
"Put the water over there.",
"They're quite thirsty.",
"Their water bottles broke."
];
string sPattern = "the(ir)?\\s";
foreach (string s in sentences)
{
Console.Write($"{s,24}");
if (System.Text.RegularExpressions.Regex.IsMatch(s, sPattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase))
{
Console.WriteLine($" (match for '{sPattern}' found)");
}
else
{
Console.WriteLine();
}
}
小窍门
搜索确切字符串时,方法 string 通常是更好的选择。 在源字符串中搜索某些模式时,正则表达式更好。
字符串是否遵循模式?
以下代码使用正则表达式来验证数组中每个字符串的格式。 验证要求将每个字符串格式为电话号码:前三组数字由短划线分隔,其中前两个组各包含三个数字,第三个组包含四个数字。 搜索模式使用正则表达式 ^\\d{3}-\\d{3}-\\d{4}$。 有关详细信息,请参阅 正则表达式语言 - 快速参考。
| 图案 | Meaning |
|---|---|
^ |
匹配字符串的开头 |
\d{3} |
完全匹配恰好三个数字字符 |
- |
匹配“-”字符 |
\d{4} |
完全匹配四个数字字符 |
$ |
匹配字符串的末尾 |
string[] numbers =
[
"123-555-0190",
"444-234-22450",
"690-555-0178",
"146-893-232",
"146-555-0122",
"4007-555-0111",
"407-555-0111",
"407-2-5555",
"407-555-8974",
"407-2ab-5555",
"690-555-8148",
"146-893-232-"
];
string sPattern = """^\d{3}-\d{3}-\d{4}$""";
foreach (string s in numbers)
{
Console.Write($"{s,14}");
if (System.Text.RegularExpressions.Regex.IsMatch(s, sPattern))
{
Console.WriteLine(" - valid");
}
else
{
Console.WriteLine(" - invalid");
}
}
这种独特的搜索模式可以匹配许多有效的字符串。 正则表达式更适合搜索或验证模式,而不是单个文本字符串。