다음을 통해 공유


Regex 클래스

변경할 수 없는 정규식을 나타냅니다.

네임스페이스: System.Text.RegularExpressions
어셈블리: System(system.dll)

구문

‘선언
<SerializableAttribute> _
Public Class Regex
    Implements ISerializable
‘사용 방법
Dim instance As Regex
[SerializableAttribute] 
public class Regex : ISerializable
[SerializableAttribute] 
public ref class Regex : ISerializable
/** @attribute SerializableAttribute() */ 
public class Regex implements ISerializable
SerializableAttribute 
public class Regex implements ISerializable

설명

Regex 클래스에는 정적 메서드가 여러 개 포함되어 있어서 Regex 개체를 명시적으로 만들지 않고도 정규식을 사용할 수 있습니다. 한번 사용한 다음 소멸시킨다는 점에서 정적 메서드를 사용하는 것은 Regex 개체를 만드는 것과 같습니다.

Regex 클래스는 변경할 수 없으며(읽기 전용) 원래 스레드로부터 안전합니다. Regex 개체는 모든 스레드에서 만들 수 있고 스레드 사이에서 공유할 수 있습니다. 자세한 내용은 스레드로부터의 안전성을 참조하십시오.

예제

다음 코드 예제에서는 정규식을 사용하여 문자열에 현재 값을 나타내는 올바른 형식이 있는지 여부를 확인하는 방법을 보여 줍니다. 여기에서는 둘러싸는 ^$ 토큰을 사용하여 부분 문자열이 아니라 전체 문자열이 정규식과 일치해야 함을 나타냅니다.

using System;
using System.Text.RegularExpressions;

public class Test
{

    public static void Main ()
    {

          // Define a regular expression for currency values.
        Regex rx = new Regex(@"^-?\d+(\.\d{2})?$");
        
        // Define some test strings.
        string[] tests = {"-42", "19.99", "0.001", "100 USD"};
        
        // Check each test string against the regular expression.
        foreach (string test in tests)
        {
            if (rx.IsMatch(test))
            {
                Console.WriteLine("{0} is a currency value.", test);
            }
            else
            {
                Console.WriteLine("{0} is not a currency value.", test);
            }
        }
       
    }   
    
}
#using <System.dll>

using namespace System;
using namespace System::Text::RegularExpressions;
int main()
{
   
   // Define a regular expression for currency values.
   Regex^ rx = gcnew Regex( "^-?\\d+(\\.\\d{2})?$" );
   
   // Define some test strings.
   array<String^>^tests = {"-42","19.99","0.001","100 USD"};
   
   // Check each test string against the regular expression.
   System::Collections::IEnumerator^ myEnum = tests->GetEnumerator();
   while ( myEnum->MoveNext() )
   {
      String^ test = safe_cast<String^>(myEnum->Current);
      if ( rx->IsMatch( test ) )
      {
         Console::WriteLine( "{0} is a currency value.", test );
      }
      else
      {
         Console::WriteLine( "{0} is not a currency value.", test );
      }
   }
}
import System.*;
import System.Text.RegularExpressions.*;

public class Test
{
    public static void main(String[] args)
    {
        // Define a regular expression for currency values.
        Regex rx = new Regex("^-?\\d+(\\.\\d{2})?$");

        // Define some test strings.
        String tests[] =  { "-42", "19.99", "0.001", "100 USD" };

        // Check each test string against the regular expression.
        for (int iCtr = 0; iCtr < tests.get_Length(); iCtr++) {
            String test = (String)tests.get_Item(iCtr);
            if (rx.IsMatch(test)) {
                Console.WriteLine("{0} is a currency value.", test);
            }
            else {
                Console.WriteLine("{0} is not a currency value.", test);
            }
        }
    } //main 
} //Test

다음 코드 예제에서는 정규식을 사용하여 문자열에서 단어가 반복적으로 나오는지 확인하는 방법을 보여 줍니다. 여기에서는 (?<word>) 구문을 사용하여 그룹에 이름을 지정하고 (\k<word>) 구문을 사용하여 식에서 나중에 해당 그룹을 참조합니다.

using System;
using System.Text.RegularExpressions;

public class Test
{

    public static void Main ()
    {

        // Define a regular expression for repeated words.
        Regex rx = new Regex(@"\b(?<word>\w+)\s+(\k<word>)\b",
          RegexOptions.Compiled | RegexOptions.IgnoreCase);

        // Define a test string.        
        string text = "The the quick brown fox  fox jumped over the lazy dog dog.";
        
        // Find matches.
        MatchCollection matches = rx.Matches(text);

        // Report the number of matches found.
        Console.WriteLine("{0} matches found.", matches.Count);

        // Report on each match.
        foreach (Match match in matches)
        {
            string word = match.Groups["word"].Value;
            int index = match.Index;
            Console.WriteLine("{0} repeated at position {1}", word, index);   
        }
        
    }
    
}
#using <System.dll>

using namespace System;
using namespace System::Text::RegularExpressions;
int main()
{
   // Define a regular expression for repeated words.
   Regex^ rx = gcnew Regex( "\\b(?<word>\\w+)\\s+(\\k<word>)\\b",static_cast<RegexOptions>(RegexOptions::Compiled | RegexOptions::IgnoreCase) );

   // Define a test string.        
   String^ text = "The the quick brown fox  fox jumped over the lazy dog dog.";

   // Find matches.
   MatchCollection^ matches = rx->Matches( text );

   // Report the number of matches found.
   Console::WriteLine( "{0} matches found.", matches->Count );

   // Report on each match.
   for each (Match^ match in matches)
   {
      String^ word = match->Groups["word"]->Value;
      int index = match->Index;
      Console::WriteLine("{0} repeated at position {1}", word, index);   
   }
}
import System.*;
import System.Text.RegularExpressions.*;

public class Test
{
    public static void main(String[] args)
    {
        // Define a regular expression for repeated words.
        Regex rx = new Regex("\\b(?<word>\\w+)\\s+(\\k<word>)\\b", 
            RegexOptions.Compiled | RegexOptions.IgnoreCase);

        // Define a test string.        
        String text = "The the quick brown fox  fox jumped over the "
            + "lazy dog dog.";

        // Find matches.
        MatchCollection matches = rx.Matches(text);

        // Report the number of matches found.
        Console.WriteLine("{0} matches found.", (Int32)matches.get_Count());

        // Report on each match.
        for (int iCtr = 0; iCtr < matches.get_Count(); iCtr++) {
            Match match = matches.get_Item(iCtr);
            String word = match.get_Groups().get_Item("word").get_Value();
            int index = match.get_Index();
            Console.WriteLine("{0} repeated at position {1}", word, 
                (Int32)index);
        }
    } //main       
} //Test

상속 계층 구조

System.Object
  System.Text.RegularExpressions.Regex
     파생 클래스

스레드로부터의 안전성

이 형식의 모든 public static(Visual Basic의 경우 Shared) 멤버는 스레드로부터 안전합니다. 인터페이스 멤버는 스레드로부터 안전하지 않습니다.

플랫폼

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

.NET Framework에서 모든 플래폼의 모든 버전을 지원하지는 않습니다. 지원되는 버전의 목록은 시스템 요구 사항을 참조하십시오.

버전 정보

.NET Framework

2.0, 1.1, 1.0에서 지원

.NET Compact Framework

2.0, 1.0에서 지원

참고 항목

참조

Regex 멤버
System.Text.RegularExpressions 네임스페이스

기타 리소스

.NET Framework 정규식
정규식 언어 요소