如何搜索字符串

可以使用两种主要策略搜索字符串中的文本。 String 类的方法搜索特定文本。 正则表达式搜索文本中的模式。

注意

本文中的 C# 示例运行在 Try.NET 内联代码运行程序和演练环境中。 选择“运行”按钮以在交互窗口中运行示例。 执行代码后,可通过再次选择“运行”来修改它并运行已修改的代码。 已修改的代码要么在交互窗口中运行,要么编译失败时,交互窗口将显示所有 C# 编译器错误消息。

string 类型是 System.String 类的别名,可提供多种有效方法用于搜索字符串的内容。 其中包括 ContainsStartsWithEndsWithIndexOf 以及 LastIndexOfSystem.Text.RegularExpressions.Regex 类具备丰富的词汇来对文本中的模式进行搜索。 你将在本文中了解这些技术以及如何选择符合需求的最佳方法。

字符串包含文本吗?

String.ContainsString.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");
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 枚举值指定区分大小写的搜索。

寻找的文本出现在字符串的什么位置?

IndexOfLastIndexOf 方法也搜索字符串中的文本。 这些方法返回查找到的文本的位置。 如果未找到文本,则返回 -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# 字符串中必须转义为 \\)。

模式 含义
the 匹配文本“the”
(eir)? 匹配 0 个或 1 个“eir”
\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 方法通常是更好的选择。 搜索源字符串中的一些模式时,正则表达式更适用。

字符串是否遵循模式?

以下代码使用正则表达式验证数组中每个字符串的格式。 验证要求每个字符串具备电话号码的形式:用短划线分隔成三组数字,前两组包含 3 个数字,而第三组包含 4 个数字。 搜索模式采用正则表达式 ^\\d{3}-\\d{3}-\\d{4}$。 有关更多信息,请参见正则表达式语言 - 快速参考

模式 含义
^ 匹配字符串的开头部分
\d{3} 完全匹配 3 位字符
- 匹配字符“-”
\d{4} 完全匹配 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");
    }
}

此单个搜索模式匹配很多有效字符串。 正则表达式更适用于搜索或验证模式,而不是单个文本字符串。

另请参阅