문자열 검색 방법

문자열에서 텍스트를 검색하는 두 가지 기본 전략을 사용할 수 있습니다. String 클래스의 메서드는 특정 텍스트를 검색합니다. 정규식은 텍스트에서 패턴을 검색합니다.

참고 항목

이 문서의 C# 예제는 Try.NET 인라인 코드 러너 및 놀이터에서 실행됩니다. 대화형 창에서 예제를 실행하려면 실행 버튼을 선택합니다. 코드를 실행하면 실행을 다시 선택하여 코드를 수정하고 수정된 코드를 실행할 수 있습니다. 수정된 코드는 대화형 창에서 실행되거나, 컴파일이 실패하면 대화형 창에 모든 C# 컴파일러 오류 메시지가 표시됩니다.

System.String 클래스의 별칭인 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");
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을 반환합니다. 다음 예제에서는 "메서드"라는 단어의 첫 번째 및 마지막 항목에 대한 검색을 보여주고, 그 사이에 텍스트를 표시합니다.

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)? “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 메서드를 사용하는 것이 좋습니다. 원본 문자열에서 몇 가지 패턴을 검색하는 경우 정규식을 사용하는 것이 좋습니다.

문자열은 패턴을 따르나요?

다음 코드는 정규식을 사용하여 배열에서 각 문자열 형식의 유효성을 검사합니다. 유효성 검사에서는 각 문자열이 전화 번호의 형식을 사용해야 합니다. 이 경우 3개의 숫자 그룹이 대시로 구분되고, 처음 두 그룹에는 세 자리 숫자가 포함되며, 세 번째 그룹에는 네 자리 숫자가 포함됩니다. 검색 패턴은 정규식 ^\\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");
    }
}

이 단일 검색 패턴은 많은 유효한 문자열과 일치합니다. 단일 텍스트 문자열이 아닌 패턴을 검색하거나 유효성을 확인하기 위해 정규식을 사용하는 것이 좋습니다.

참고 항목