다음을 통해 공유


Regex.Replace 메서드

정의

지정된 입력 문자열에서 정규식 패턴과 일치하는 문자열을 지정된 대체 문자열로 대체합니다.

오버로드

Replace(String, MatchEvaluator, Int32, Int32)

지정된 입력 부분 문자열에서 정규식 패턴과 일치하는 지정된 최대 문자열 수를 MatchEvaluator 대리자가 반환한 문자열로 대체합니다.

Replace(String, String, String)

지정된 입력 문자열에서 지정된 정규식과 일치하는 모든 문자열을 지정된 대체 문자열로 대체합니다.

Replace(String, String, MatchEvaluator, RegexOptions, TimeSpan)

지정된 입력 문자열에서 지정된 정규식과 일치하는 모든 부분 문자열을 MatchEvaluator 대리자가 반환한 문자열로 대체합니다. 일치 작업을 수정하는 옵션과 일치하는 항목이 없는 경우 시간 제한 간격을 지정하는 추가 매개 변수가 있습니다.

Replace(String, String, MatchEvaluator, RegexOptions)

지정된 입력 문자열에서 지정된 정규식과 일치하는 모든 문자열을 MatchEvaluator 대리자가 반환한 문자열로 대체합니다. 지정한 옵션은 일치 작업을 수정합니다.

Replace(String, String, String, RegexOptions, TimeSpan)

지정된 입력 문자열에서 지정된 정규식과 일치하는 모든 문자열을 지정된 대체 문자열로 대체합니다. 일치 작업을 수정하는 옵션과 일치하는 항목이 없는 경우 시간 제한 간격을 지정하는 추가 매개 변수가 있습니다.

Replace(String, String, String, RegexOptions)

지정된 입력 문자열에서 지정된 정규식과 일치하는 모든 문자열을 지정된 대체 문자열로 대체합니다. 지정한 옵션은 일치 작업을 수정합니다.

Replace(String, MatchEvaluator)

지정된 입력 문자열에서 지정된 정규식과 일치하는 모든 문자열을 MatchEvaluator 대리자가 반환한 문자열로 대체합니다.

Replace(String, MatchEvaluator, Int32)

지정된 입력 문자열에서 정규식 패턴과 일치하는 지정된 최대 문자열 수를 MatchEvaluator 대리자가 반환한 문자열로 대체합니다.

Replace(String, String, MatchEvaluator)

지정된 입력 문자열에서 지정된 정규식과 일치하는 모든 문자열을 MatchEvaluator 대리자가 반환한 문자열로 대체합니다.

Replace(String, String, Int32)

지정된 입력 문자열에서 정규식 패턴과 일치하는 지정된 최대 문자열 수를 지정된 대체 문자열로 대체합니다.

Replace(String, String)

지정된 입력 문자열에서 정규식 패턴과 일치하는 모든 문자열을 지정된 대체 문자열로 대체합니다.

Replace(String, String, Int32, Int32)

지정된 입력 부분 문자열에서 정규식 패턴과 일치하는 지정된 최대 문자열 수를 지정된 대체 문자열로 대체합니다.

Replace(String, MatchEvaluator, Int32, Int32)

Source:
Regex.Replace.cs
Source:
Regex.Replace.cs
Source:
Regex.Replace.cs

지정된 입력 부분 문자열에서 정규식 패턴과 일치하는 지정된 최대 문자열 수를 MatchEvaluator 대리자가 반환한 문자열로 대체합니다.

public:
 System::String ^ Replace(System::String ^ input, System::Text::RegularExpressions::MatchEvaluator ^ evaluator, int count, int startat);
public string Replace (string input, System.Text.RegularExpressions.MatchEvaluator evaluator, int count, int startat);
member this.Replace : string * System.Text.RegularExpressions.MatchEvaluator * int * int -> string
Public Function Replace (input As String, evaluator As MatchEvaluator, count As Integer, startat As Integer) As String

매개 변수

input
String

일치 항목을 검색할 문자열입니다.

evaluator
MatchEvaluator

각 일치 항목을 검사하고 일치하는 원래 문자열 또는 대체 문자열을 반환하는 사용자 지정 메서드입니다.

count
Int32

교체가 발생하는 최대 횟수입니다.

startat
Int32

검색이 시작되는 입력 문자열의 문자 위치입니다.

반환

대체 문자열이 일치하는 각 문자열을 대신한다는 점을 제외하고 입력 문자열과 동일한 새 문자열입니다. 정규식 패턴이 현재 인스턴스에서 일치하지 않으면 메서드는 변경되지 않은 현재 인스턴스를 반환합니다.

예외

input 또는 evaluatornull.

startat 0보다 작거나 input길이보다 큽니다.

시간 초과가 발생했습니다. 제한 시간에 대한 자세한 내용은 주의 섹션을 참조하세요.

설명

Regex.Replace(String, MatchEvaluator, Int32, Int32) 메서드는 다음 조건 중 하나라도 충족되는 경우 정규식 일치를 바꾸는 데 유용합니다.

  • 정규식 대체 패턴으로 대체 문자열을 쉽게 지정할 수 없습니다.
  • 대체 문자열은 일치하는 문자열에서 수행된 일부 처리로 인해 발생합니다.
  • 대체 문자열은 조건부 처리로 인해 발생합니다.

이 메서드는 Regex.Matches(String, Int32) 메서드를 호출하고 반환된 MatchCollection 컬렉션의 첫 번째 countMatch 개체를 evaluator 대리자에게 전달하는 것과 같습니다.

startat대한 자세한 내용은 Match(String, Int32)주의 섹션을 참조하세요.

정규식은 현재 Regex 개체에 대한 생성자가 정의한 패턴입니다.

evaluator 매개 변수는 사용자가 정의하고 각 일치 항목을 검사하는 사용자 지정 메서드의 대리자입니다. MatchEvaluator 대리자를 일치하려면 사용자 지정 메서드에 다음 서명이 있어야 합니다.

public string MatchEvaluatorMethod(Match match)
Public Function MatchEvaluatorMethod(match As Match) As String

사용자 지정 메서드는 일치하는 입력을 대체하는 문자열을 반환합니다.

대체 작업의 실행 시간이 Regex.Regex(String, RegexOptions, TimeSpan) 생성자가 지정한 제한 시간 간격을 초과하면 RegexMatchTimeoutException 예외가 throw됩니다. 생성자를 호출할 때 제한 시간 간격을 설정하지 않으면 작업이 Regex 개체가 만들어진 애플리케이션 도메인에 대해 설정된 제한 시간 값을 초과하면 예외가 throw됩니다. Regex 생성자 호출 또는 애플리케이션 도메인의 속성에 제한 시간이 정의되지 않거나 제한 시간 값이 Regex.InfiniteMatchTimeout경우 예외가 throw되지 않습니다.

일치하는 항목이 없으면 메서드가 변경되지 input 반환하므로 Object.ReferenceEquals 메서드를 사용하여 메서드가 입력 문자열을 대체했는지 여부를 확인할 수 있습니다.

추가 정보

적용 대상

Replace(String, String, String)

Source:
Regex.Replace.cs
Source:
Regex.Replace.cs
Source:
Regex.Replace.cs

지정된 입력 문자열에서 지정된 정규식과 일치하는 모든 문자열을 지정된 대체 문자열로 대체합니다.

public:
 static System::String ^ Replace(System::String ^ input, System::String ^ pattern, System::String ^ replacement);
public static string Replace (string input, string pattern, string replacement);
static member Replace : string * string * string -> string
Public Shared Function Replace (input As String, pattern As String, replacement As String) As String

매개 변수

input
String

일치 항목을 검색할 문자열입니다.

pattern
String

일치시킬 정규식 패턴입니다.

replacement
String

대체 문자열입니다.

반환

대체 문자열이 일치하는 각 문자열을 대신한다는 점을 제외하고 입력 문자열과 동일한 새 문자열입니다. 현재 인스턴스에서 pattern 일치하지 않으면 메서드는 변경되지 않은 현재 인스턴스를 반환합니다.

예외

정규식 구문 분석 오류가 발생했습니다.

input, pattern또는 replacementnull.

시간 초과가 발생했습니다. 제한 시간에 대한 자세한 내용은 주의 섹션을 참조하세요.

예제

다음 예제에서는 하나 이상의 공백 문자와 일치하는 정규식 \s+정의합니다. 대체 문자열 "은 단일 공백 문자로 바꿉니다.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string input = "This is   text with   far  too   much   " + 
                     "white space.";
      string pattern = "\\s+";
      string replacement = " ";
      string result = Regex.Replace(input, pattern, replacement);
      
      Console.WriteLine("Original String: {0}", input);
      Console.WriteLine("Replacement String: {0}", result);                             
   }
}
// The example displays the following output:
//       Original String: This is   text with   far  too   much   white space.
//       Replacement String: This is text with far too much white space.
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim input As String = "This is   text with   far  too   much   " + _
                            "white space."
      Dim pattern As String = "\s+"
      Dim replacement As String = " "
      Dim result As String = Regex.Replace(input, pattern, replacement)
      
      Console.WriteLine("Original String: {0}", input)
      Console.WriteLine("Replacement String: {0}", result)                             
   End Sub
End Module
' The example displays the following output:
'          Original String: This is   text with   far  too   much   white space.
'          Replacement String: This is text with far too much white space.

다음 예제에서는 Replace(String, String, String) 메서드를 사용하여 UNC 경로의 로컬 컴퓨터 및 드라이브 이름을 로컬 파일 경로로 바꿉니다. 정규식은 Environment.MachineName 속성을 사용하여 로컬 컴퓨터의 이름과 논리 드라이브의 이름을 포함하는 Environment.GetLogicalDrives 메서드를 포함합니다. 예제를 성공적으로 실행하려면 리터럴 문자열 "MyMachine"을 로컬 컴퓨터 이름으로 바꿔야 합니다.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      // Get drives available on local computer and form into a single character expression.
      string[] drives = Environment.GetLogicalDrives();
      string driveNames = String.Empty;
      foreach (string drive in drives)
         driveNames += drive.Substring(0,1);
      // Create regular expression pattern dynamically based on local machine information.
      string pattern = @"\\\\(?i:" + Environment.MachineName + @")(?:\.\w+)*\\((?i:[" + driveNames + @"]))\$";

      string replacement = "$1:";
      string[] uncPaths = { @"\\MyMachine.domain1.mycompany.com\C$\ThingsToDo.txt", 
                            @"\\MyMachine\c$\ThingsToDo.txt", 
                            @"\\MyMachine\d$\documents\mydocument.docx" }; 
      
      foreach (string uncPath in uncPaths)
      {
         Console.WriteLine("Input string: " + uncPath);
         Console.WriteLine("Returned string: " + Regex.Replace(uncPath, pattern, replacement));
         Console.WriteLine();
      }
   }
}
// The example displays the following output if run on a machine whose name is
// MyMachine:
//    Input string: \\MyMachine.domain1.mycompany.com\C$\ThingsToTo.txt
//    Returned string: C:\ThingsToDo.txt
//    
//    Input string: \\MyMachine\c$\ThingsToDo.txt
//    Returned string: c:\ThingsToDo.txt
//    
//    Input string: \\MyMachine\d$\documents\mydocument.docx
//    Returned string: d:\documents\mydocument.docx
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      ' Get drives available on local computer and form into a single character expression.
      Dim drives() As String = Environment.GetLogicalDrives()
      Dim driveNames As String = Nothing
      For Each drive As String In drives
         driveNames += drive.Substring(0,1)
      Next
      ' Create regular expression pattern dynamically based on local machine information.
      Dim pattern As String = "\\\\(?i:" + Environment.MachineName + ")(?:\.\w+)*\\((?i:[" + driveNames + "]))\$"

      Dim replacement As String = "$1:"
      Dim uncPaths() AS String = {"\\MyMachine.domain1.mycompany.com\C$\ThingsToDo.txt", _
                                  "\\MyMachine\c$\ThingsToDo.txt", _
                                  "\\MyMachine\d$\documents\mydocument.docx" } 
      
      For Each uncPath As String In uncPaths
         Console.WriteLine("Input string: " + uncPath)
         Console.WriteLine("Returned string: " + Regex.Replace(uncPath, pattern, replacement))
         Console.WriteLine()
      Next
   End Sub
End Module
' The example displays the following output if run on a machine whose name is
' MyMachine:
'    Input string: \\MyMachine.domain1.mycompany.com\C$\ThingsToTo.txt
'    Returned string: C:\ThingsToDo.txt
'    
'    Input string: \\MyMachine\c$\ThingsToDo.txt
'    Returned string: c:\ThingsToDo.txt
'    
'    Input string: \\MyMachine\d$\documents\mydocument.docx
'    Returned string: d:\documents\mydocument.docx

정규식 패턴은 다음 식으로 정의됩니다.

"\\\\(?i:" + Environment.MachineName + ")(?:\.\w+)*\\((?i:[" + driveNames + "]))\$"

다음 표에서는 정규식 패턴이 해석되는 방법을 보여 줍니다.

무늬 묘사
\\\\ 두 개의 연속 백슬래시(\) 문자를 일치합니다. 백슬래시 문자는 이스케이프 문자로 해석되므로 각 백슬래시는 다른 백슬래시로 이스케이프되어야 합니다.
(?i:" + Environment.MachineName + ") Environment.MachineName 속성에서 반환되는 문자열의 대/소문자를 구분하지 않는 일치를 수행합니다.
(?:\.\w+)* 마침표(.) 문자 뒤에 하나 이상의 단어 문자를 찾습니다. 이 일치는 0회 이상 발생할 수 있습니다. 일치하는 하위 식이 캡처되지 않습니다.
\\ 백슬래시(\) 문자를 일치합니다.
((?i:[" + driveNames + "])) 개별 드라이브 문자로 구성된 문자 클래스의 대/소문자를 구분하지 않는 일치를 수행합니다. 이 일치는 캡처된 첫 번째 하위 식입니다.
\$ 리터럴 달러 기호($) 문자와 일치합니다.

$1 대체 패턴은 전체 일치 항목을 캡처된 첫 번째 하위 식으로 바꿉니다. 즉, UNC 컴퓨터 및 드라이브 이름을 드라이브 문자로 바꿉니다.

설명

정적 Replace 메서드는 지정된 정규식 패턴을 사용하여 Regex 개체를 생성하고 인스턴스 메서드를 Replace호출하는 것과 같습니다.

pattern 매개 변수는 일치시킬 문자열을 상징적으로 설명하는 정규식 언어 요소로 구성됩니다. 정규식에 대한 자세한 내용은 .NET 정규식정규식 언어 - 빠른 참조참조하세요. 일치 항목 검색은 input 문자열의 시작 부분에서 시작됩니다.

replacement 매개 변수는 input각 일치 항목을 바꿀 문자열을 지정합니다. replacement 리터럴 텍스트와 대체조합으로 구성 될 수 있습니다. 예를 들어 a*${test}b 대체 패턴은 문자열 "a*"를 삽입한 다음 test 캡처링 그룹과 일치하는 부분 문자열(있는 경우) 뒤에 문자열 "b"를 삽입합니다. * 문자는 대체 패턴 내에서 메타 문자로 인식되지 않습니다.

메모

대체는 대체 패턴에서 인식되는 유일한 정규식 언어 요소입니다. 문자 이스케이프를 비롯한 다른 모든 정규식 언어 요소는 정규식 패턴에서만 허용되며 대체 패턴에서는 인식되지 않습니다.

대체 작업의 실행 시간이 메서드가 호출되는 애플리케이션 도메인에 대해 지정된 제한 시간 간격을 초과하면 RegexMatchTimeoutException 예외가 throw됩니다. 애플리케이션 도메인의 속성에 제한 시간이 정의되어 있지 않거나 시간 제한 값이 Regex.InfiniteMatchTimeout경우 예외가 throw되지 않습니다.

일치하는 항목이 없으면 메서드가 변경되지 input 반환하므로 Object.ReferenceEquals 메서드를 사용하여 메서드가 입력 문자열을 대체했는지 여부를 확인할 수 있습니다.

호출자 참고

이 메서드는 호출되는 애플리케이션 도메인의 기본 제한 시간 값과 동일한 간격 후에 시간 초과됩니다. 애플리케이션 도메인에 대해 제한 시간 값이 정의되지 않은 경우 메서드의 시간 초과를 방지하는 InfiniteMatchTimeout값이 사용됩니다. 패턴 일치를 바꾸는 데 권장되는 정적 메서드는 Replace(String, String, String, RegexOptions, TimeSpan)제한 시간 간격을 설정할 수 있습니다.

추가 정보

  • 정규식 대체
  • 정규식 언어 요소

적용 대상

Replace(String, String, MatchEvaluator, RegexOptions, TimeSpan)

Source:
Regex.Replace.cs
Source:
Regex.Replace.cs
Source:
Regex.Replace.cs

지정된 입력 문자열에서 지정된 정규식과 일치하는 모든 부분 문자열을 MatchEvaluator 대리자가 반환한 문자열로 대체합니다. 일치 작업을 수정하는 옵션과 일치하는 항목이 없는 경우 시간 제한 간격을 지정하는 추가 매개 변수가 있습니다.

public:
 static System::String ^ Replace(System::String ^ input, System::String ^ pattern, System::Text::RegularExpressions::MatchEvaluator ^ evaluator, System::Text::RegularExpressions::RegexOptions options, TimeSpan matchTimeout);
public static string Replace (string input, string pattern, System.Text.RegularExpressions.MatchEvaluator evaluator, System.Text.RegularExpressions.RegexOptions options, TimeSpan matchTimeout);
static member Replace : string * string * System.Text.RegularExpressions.MatchEvaluator * System.Text.RegularExpressions.RegexOptions * TimeSpan -> string
Public Shared Function Replace (input As String, pattern As String, evaluator As MatchEvaluator, options As RegexOptions, matchTimeout As TimeSpan) As String

매개 변수

input
String

일치 항목을 검색할 문자열입니다.

pattern
String

일치시킬 정규식 패턴입니다.

evaluator
MatchEvaluator

각 일치 항목을 검사하고 일치하는 원래 문자열 또는 대체 문자열을 반환하는 사용자 지정 메서드입니다.

options
RegexOptions

일치 옵션을 제공하는 열거형 값의 비트 조합입니다.

matchTimeout
TimeSpan

제한 시간 간격 또는 메서드가 시간 초과되지 않아야 함을 나타내는 InfiniteMatchTimeout.

반환

대체 문자열이 일치하는 각 문자열을 대신한다는 점을 제외하고 입력 문자열과 동일한 새 문자열입니다. 현재 인스턴스에서 pattern 일치하지 않으면 메서드는 변경되지 않은 현재 인스턴스를 반환합니다.

예외

정규식 구문 분석 오류가 발생했습니다.

input, pattern또는 evaluatornull.

options RegexOptions 값의 유효한 비트 조합이 아닙니다.

-또는-

matchTimeout 음수, 0 또는 약 24일보다 큽니다.

시간 초과가 발생했습니다. 제한 시간에 대한 자세한 내용은 주의 섹션을 참조하세요.

예제

다음 예제에서는 정규식을 사용하여 문자열에서 개별 단어를 추출한 다음 MatchEvaluator 대리자를 사용하여 단어의 개별 문자를 스크램블링하는 WordScramble 메서드를 호출합니다. 이를 위해 WordScramble 메서드는 일치 항목의 문자를 포함하는 배열을 만듭니다. 또한 임의 부동 소수점 숫자로 채우는 병렬 배열을 만듭니다. 배열은 Array.Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>) 메서드를 호출하여 정렬되고 정렬된 배열은 String 클래스 생성자에 대한 인수로 제공됩니다. 새로 만든 이 문자열은 WordScramble 메서드에서 반환됩니다. 정규식 패턴 \w+ 하나 이상의 단어 문자와 일치합니다. 정규식 엔진은 공백 문자와 같은 단어가 아닌 문자를 발견할 때까지 일치 항목에 문자를 계속 추가합니다. Replace(String, String, MatchEvaluator, RegexOptions) 메서드 호출에는 정규식 패턴 \w+ # Matches all the characters in a word. 주석이 정규식 엔진에서 무시되도록 RegexOptions.IgnorePatternWhitespace 옵션이 포함됩니다.

using System;
using System.Collections;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string words = "letter alphabetical missing lack release " + 
                     "penchant slack acryllic laundry cease";
      string pattern = @"\w+  # Matches all the characters in a word.";                            
      MatchEvaluator evaluator = new MatchEvaluator(WordScrambler);
      Console.WriteLine("Original words:");
      Console.WriteLine(words);
      Console.WriteLine();
      try {
         Console.WriteLine("Scrambled words:");
         Console.WriteLine(Regex.Replace(words, pattern, evaluator, 
                                         RegexOptions.IgnorePatternWhitespace,
                                         TimeSpan.FromSeconds(.25)));      
      }
      catch (RegexMatchTimeoutException) {
         Console.WriteLine("Word Scramble operation timed out.");
         Console.WriteLine("Returned words:");
      }
   }

   public static string WordScrambler(Match match)
   {
      int arraySize = match.Value.Length;
      // Define two arrays equal to the number of letters in the match.
      double[] keys = new double[arraySize];
      char[] letters = new char[arraySize];
      
      // Instantiate random number generator'
      Random rnd = new Random();
      
      for (int ctr = 0; ctr < match.Value.Length; ctr++)
      {
         // Populate the array of keys with random numbers.
         keys[ctr] = rnd.NextDouble();
         // Assign letter to array of letters.
         letters[ctr] = match.Value[ctr];
      }         
      Array.Sort(keys, letters, 0, arraySize, Comparer.Default);      
      return new String(letters);
   }
}
// The example displays output similar to the following:
//    Original words:
//    letter alphabetical missing lack release penchant slack acryllic laundry cease
//    
//    Scrambled words:
//    etlert liahepalbcat imsgsni alkc ereelsa epcnnaht lscak cayirllc alnyurd ecsae
Imports System.Collections
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim words As String = "letter alphabetical missing lack release " + _
                            "penchant slack acryllic laundry cease"
      Dim pattern As String = "\w+  # Matches all the characters in a word."                            
      Dim evaluator As MatchEvaluator = AddressOf WordScrambler
      Console.WriteLine("Original words:")
      Console.WriteLine(words)
      Try
         Console.WriteLine("Scrambled words:")
         Console.WriteLine(Regex.Replace(words, pattern, evaluator,
                                         RegexOptions.IgnorePatternWhitespace,
                                         TimeSpan.FromSeconds(.25)))      
      Catch e As RegexMatchTimeoutException
         Console.WriteLine("Word Scramble operation timed out.")
         Console.WriteLine("Returned words:")
      End Try   
   End Sub
   
   Public Function WordScrambler(match As Match) As String
      Dim arraySize As Integer = match.Value.Length - 1
      ' Define two arrays equal to the number of letters in the match.
      Dim keys(arraySize) As Double
      Dim letters(arraySize) As Char
      
      ' Instantiate random number generator'
      Dim rnd As New Random()
      
      For ctr As Integer = 0 To match.Value.Length - 1
         ' Populate the array of keys with random numbers.
         keys(ctr) = rnd.NextDouble()
         ' Assign letter to array of letters.
         letters(ctr) = match.Value.Chars(ctr)
      Next         
      Array.Sort(keys, letters, 0, arraySize, Comparer.Default)      
      Return New String(letters)
   End Function
End Module
' The example displays output similar to the following:
'    Original words:
'    letter alphabetical missing lack release penchant slack acryllic laundry cease
'    
'    Scrambled words:
'    etlert liahepalbcat imsgsni alkc ereelsa epcnnaht lscak cayirllc alnyurd ecsae

설명

Regex.Replace(String, String, MatchEvaluator, RegexOptions) 메서드는 다음 조건 중 하나라도 충족되는 경우 정규식 일치를 바꾸는 데 유용합니다.

  • 정규식 대체 패턴으로 대체 문자열을 쉽게 지정할 수 없는 경우

  • 일치하는 문자열에서 수행된 일부 처리에서 대체 문자열이 발생하는 경우

  • 대체 문자열이 조건부 처리에서 발생하는 경우

이 메서드는 Regex.Matches(String, String, RegexOptions) 메서드를 호출하고 반환된 MatchCollection 컬렉션의 각 Match 개체를 evaluator 대리자에게 전달하는 것과 같습니다.

pattern 매개 변수는 일치시킬 문자열을 상징적으로 설명하는 정규식 언어 요소로 구성됩니다. 정규식에 대한 자세한 내용은 .NET 정규식정규식 언어 - 빠른 참조참조하세요.

evaluator 매개 변수는 사용자가 정의하고 각 일치 항목을 검사하는 사용자 지정 메서드의 대리자입니다. MatchEvaluator 대리자를 일치하려면 사용자 지정 메서드에 다음 서명이 있어야 합니다.

public string MatchEvaluatorMethod(Match match)
Public Function MatchEvaluatorMethod(match As Match) As String

사용자 지정 메서드는 일치하는 입력을 대체하는 문자열을 반환합니다.

options 매개 변수에 대한 RightToLeft 지정하면 입력 문자열의 끝에서 일치 항목 검색이 시작되고 왼쪽으로 이동합니다. 그렇지 않으면 입력 문자열의 시작 부분에 검색이 시작되고 오른쪽으로 이동합니다.

matchTimeout 매개 변수는 패턴 일치 메서드가 시간이 초과되기 전에 일치 항목을 찾으려고 시도하는 기간을 지정합니다. 제한 시간 간격을 설정하면 과도한 역추적을 사용하는 정규식이 "거의 일치하는 항목이 포함된 입력을 처리할 때 응답을 중지합니다. 자세한 내용은 정규식 및 역추적대한 모범 사례를 참조하세요. 해당 시간 간격에 일치하는 항목이 없으면 메서드는 RegexMatchTimeoutException 예외를 throw합니다. matchTimeout 메서드가 실행되는 애플리케이션 도메인에 대해 정의된 기본 제한 시간 값을 재정의합니다.

일치하는 항목이 없으면 메서드가 변경되지 input 반환하므로 Object.ReferenceEquals 메서드를 사용하여 메서드가 입력 문자열을 대체했는지 여부를 확인할 수 있습니다.

호출자 참고

matchTimeout 매개 변수를 2초와 같은 적절한 값으로 설정하는 것이 좋습니다. InfiniteMatchTimeout지정하여 시간 초과를 사용하지 않도록 설정하면 정규식 엔진이 약간 더 나은 성능을 제공합니다. 그러나 다음 조건에서만 시간 초과를 사용하지 않도록 설정해야 합니다.

  • 정규식에서 처리된 입력이 알려진 신뢰할 수 있는 원본에서 파생되거나 정적 텍스트로 구성된 경우 사용자가 동적으로 입력한 텍스트는 제외됩니다.

  • 정규식 패턴을 철저히 테스트하여 일치 항목, 비 일치 항목 및 근사 일치 항목을 효율적으로 처리하는지 확인합니다.

  • 정규식 패턴에 거의 일치 항목을 처리할 때 과도한 역추적을 일으키는 것으로 알려진 언어 요소가 없는 경우

추가 정보

  • RegexOptions
  • 정규식 대체
  • 정규식 언어 요소
  • 정규식 역추적
  • .NET 정규식에 대한 모범 사례

적용 대상

Replace(String, String, MatchEvaluator, RegexOptions)

Source:
Regex.Replace.cs
Source:
Regex.Replace.cs
Source:
Regex.Replace.cs

지정된 입력 문자열에서 지정된 정규식과 일치하는 모든 문자열을 MatchEvaluator 대리자가 반환한 문자열로 대체합니다. 지정한 옵션은 일치 작업을 수정합니다.

public:
 static System::String ^ Replace(System::String ^ input, System::String ^ pattern, System::Text::RegularExpressions::MatchEvaluator ^ evaluator, System::Text::RegularExpressions::RegexOptions options);
public static string Replace (string input, string pattern, System.Text.RegularExpressions.MatchEvaluator evaluator, System.Text.RegularExpressions.RegexOptions options);
static member Replace : string * string * System.Text.RegularExpressions.MatchEvaluator * System.Text.RegularExpressions.RegexOptions -> string
Public Shared Function Replace (input As String, pattern As String, evaluator As MatchEvaluator, options As RegexOptions) As String

매개 변수

input
String

일치 항목을 검색할 문자열입니다.

pattern
String

일치시킬 정규식 패턴입니다.

evaluator
MatchEvaluator

각 일치 항목을 검사하고 일치하는 원래 문자열 또는 대체 문자열을 반환하는 사용자 지정 메서드입니다.

options
RegexOptions

일치 옵션을 제공하는 열거형 값의 비트 조합입니다.

반환

대체 문자열이 일치하는 각 문자열을 대신한다는 점을 제외하고 입력 문자열과 동일한 새 문자열입니다. 현재 인스턴스에서 pattern 일치하지 않으면 메서드는 변경되지 않은 현재 인스턴스를 반환합니다.

예외

정규식 구문 분석 오류가 발생했습니다.

input, pattern또는 evaluatornull.

options RegexOptions 값의 유효한 비트 조합이 아닙니다.

시간 초과가 발생했습니다. 제한 시간에 대한 자세한 내용은 주의 섹션을 참조하세요.

예제

다음 예제에서는 정규식을 사용하여 문자열에서 개별 단어를 추출한 다음 MatchEvaluator 대리자를 사용하여 단어의 개별 문자를 스크램블링하는 WordScramble 메서드를 호출합니다. 이를 위해 WordScramble 메서드는 일치 항목의 문자를 포함하는 배열을 만듭니다. 또한 임의 부동 소수점 숫자로 채우는 병렬 배열을 만듭니다. 배열은 Array.Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>) 메서드를 호출하여 정렬되고 정렬된 배열은 String 클래스 생성자에 대한 인수로 제공됩니다. 새로 만든 이 문자열은 WordScramble 메서드에서 반환됩니다. 정규식 패턴 \w+ 하나 이상의 단어 문자와 일치합니다. 정규식 엔진은 공백 문자와 같은 단어가 아닌 문자를 발견할 때까지 일치 항목에 문자를 계속 추가합니다. Replace(String, String, MatchEvaluator, RegexOptions) 메서드 호출에는 정규식 패턴 \w+ # Matches all the characters in a word. 주석이 정규식 엔진에서 무시되도록 RegexOptions.IgnorePatternWhitespace 옵션이 포함됩니다.

using System;
using System.Collections;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string words = "letter alphabetical missing lack release " + 
                     "penchant slack acryllic laundry cease";
      string pattern = @"\w+  # Matches all the characters in a word.";                            
      MatchEvaluator evaluator = new MatchEvaluator(WordScrambler);
      Console.WriteLine("Original words:");
      Console.WriteLine(words);
      Console.WriteLine();
      Console.WriteLine("Scrambled words:");
      Console.WriteLine(Regex.Replace(words, pattern, evaluator, 
                                      RegexOptions.IgnorePatternWhitespace));      
   }

   public static string WordScrambler(Match match)
   {
      int arraySize = match.Value.Length;
      // Define two arrays equal to the number of letters in the match.
      double[] keys = new double[arraySize];
      char[] letters = new char[arraySize];
      
      // Instantiate random number generator'
      Random rnd = new Random();
      
      for (int ctr = 0; ctr < match.Value.Length; ctr++)
      {
         // Populate the array of keys with random numbers.
         keys[ctr] = rnd.NextDouble();
         // Assign letter to array of letters.
         letters[ctr] = match.Value[ctr];
      }         
      Array.Sort(keys, letters, 0, arraySize, Comparer.Default);      
      return new String(letters);
   }
}
// The example displays output similar to the following:
//    Original words:
//    letter alphabetical missing lack release penchant slack acryllic laundry cease
//    
//    Scrambled words:
//    etlert liahepalbcat imsgsni alkc ereelsa epcnnaht lscak cayirllc alnyurd ecsae
Imports System.Collections
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim words As String = "letter alphabetical missing lack release " + _
                            "penchant slack acryllic laundry cease"
      Dim pattern As String = "\w+  # Matches all the characters in a word."                            
      Dim evaluator As MatchEvaluator = AddressOf WordScrambler
      Console.WriteLine("Original words:")
      Console.WriteLine(words)
      Console.WriteLine("Scrambled words:")
      Console.WriteLine(Regex.Replace(words, pattern, evaluator,
                                      RegexOptions.IgnorePatternWhitespace))      
   End Sub
   
   Public Function WordScrambler(match As Match) As String
      Dim arraySize As Integer = match.Value.Length - 1
      ' Define two arrays equal to the number of letters in the match.
      Dim keys(arraySize) As Double
      Dim letters(arraySize) As Char
      
      ' Instantiate random number generator'
      Dim rnd As New Random()
      
      For ctr As Integer = 0 To match.Value.Length - 1
         ' Populate the array of keys with random numbers.
         keys(ctr) = rnd.NextDouble()
         ' Assign letter to array of letters.
         letters(ctr) = match.Value.Chars(ctr)
      Next         
      Array.Sort(keys, letters, 0, arraySize, Comparer.Default)      
      Return New String(letters)
   End Function
End Module
' The example displays output similar to the following:
'    Original words:
'    letter alphabetical missing lack release penchant slack acryllic laundry cease
'    
'    Scrambled words:
'    etlert liahepalbcat imsgsni alkc ereelsa epcnnaht lscak cayirllc alnyurd ecsae

설명

Regex.Replace(String, String, MatchEvaluator, RegexOptions) 메서드는 다음 조건 중 하나라도 true인 경우 정규식 일치를 바꾸는 데 유용합니다.

  • 정규식 대체 패턴으로 대체 문자열을 쉽게 지정할 수 없습니다.

  • 대체 문자열은 일치하는 문자열에서 수행된 일부 처리로 인해 발생합니다.

  • 대체 문자열은 조건부 처리로 인해 발생합니다.

이 메서드는 Regex.Matches(String, String, RegexOptions) 메서드를 호출하고 반환된 MatchCollection 컬렉션의 각 Match 개체를 evaluator 대리자에게 전달하는 것과 같습니다.

pattern 매개 변수는 일치시킬 문자열을 상징적으로 설명하는 정규식 언어 요소로 구성됩니다. 정규식에 대한 자세한 내용은 .NET 정규식정규식 언어 - 빠른 참조참조하세요.

evaluator 매개 변수는 사용자가 정의하고 각 일치 항목을 검사하는 사용자 지정 메서드의 대리자입니다. MatchEvaluator 대리자를 일치하려면 사용자 지정 메서드에 다음 서명이 있어야 합니다.

public string MatchEvaluatorMethod(Match match)
Public Function MatchEvaluatorMethod(match As Match) As String

사용자 지정 메서드는 일치하는 입력을 대체하는 문자열을 반환합니다.

options 매개 변수에 대한 RightToLeft 지정하면 입력 문자열의 끝에서 일치 항목 검색이 시작되고 왼쪽으로 이동합니다. 그렇지 않으면 입력 문자열의 시작 부분에 검색이 시작되고 오른쪽으로 이동합니다.

대체 작업의 실행 시간이 메서드가 호출되는 애플리케이션 도메인에 대해 지정된 제한 시간 간격을 초과하면 RegexMatchTimeoutException 예외가 throw됩니다. 애플리케이션 도메인의 속성에 제한 시간이 정의되어 있지 않거나 시간 제한 값이 Regex.InfiniteMatchTimeout경우 예외가 throw되지 않습니다.

일치하는 항목이 없으면 메서드가 변경되지 input 반환하므로 Object.ReferenceEquals 메서드를 사용하여 메서드가 입력 문자열을 대체했는지 여부를 확인할 수 있습니다.

추가 정보

적용 대상

Replace(String, String, String, RegexOptions, TimeSpan)

Source:
Regex.Replace.cs
Source:
Regex.Replace.cs
Source:
Regex.Replace.cs

지정된 입력 문자열에서 지정된 정규식과 일치하는 모든 문자열을 지정된 대체 문자열로 대체합니다. 일치 작업을 수정하는 옵션과 일치하는 항목이 없는 경우 시간 제한 간격을 지정하는 추가 매개 변수가 있습니다.

public:
 static System::String ^ Replace(System::String ^ input, System::String ^ pattern, System::String ^ replacement, System::Text::RegularExpressions::RegexOptions options, TimeSpan matchTimeout);
public static string Replace (string input, string pattern, string replacement, System.Text.RegularExpressions.RegexOptions options, TimeSpan matchTimeout);
static member Replace : string * string * string * System.Text.RegularExpressions.RegexOptions * TimeSpan -> string
Public Shared Function Replace (input As String, pattern As String, replacement As String, options As RegexOptions, matchTimeout As TimeSpan) As String

매개 변수

input
String

일치 항목을 검색할 문자열입니다.

pattern
String

일치시킬 정규식 패턴입니다.

replacement
String

대체 문자열입니다.

options
RegexOptions

일치 옵션을 제공하는 열거형 값의 비트 조합입니다.

matchTimeout
TimeSpan

제한 시간 간격 또는 메서드가 시간 초과되지 않아야 함을 나타내는 InfiniteMatchTimeout.

반환

대체 문자열이 일치하는 각 문자열을 대신한다는 점을 제외하고 입력 문자열과 동일한 새 문자열입니다. 현재 인스턴스에서 pattern 일치하지 않으면 메서드는 변경되지 않은 현재 인스턴스를 반환합니다.

예외

정규식 구문 분석 오류가 발생했습니다.

input, pattern또는 replacementnull.

options RegexOptions 값의 유효한 비트 조합이 아닙니다.

-또는-

matchTimeout 음수, 0 또는 약 24일보다 큽니다.

시간 초과가 발생했습니다. 제한 시간에 대한 자세한 내용은 주의 섹션을 참조하세요.

예제

다음 예제에서는 Replace(String, String, String, RegexOptions, TimeSpan) 메서드를 사용하여 UNC 경로의 로컬 컴퓨터 및 드라이브 이름을 로컬 파일 경로로 바꿉니다. 정규식은 Environment.MachineName 속성을 사용하여 로컬 컴퓨터의 이름과 논리 드라이브의 이름을 포함하는 Environment.GetLogicalDrives 메서드를 포함합니다. 모든 정규식 문자열 비교는 대/소문자를 구분하지 않으며 일치 항목을 0.5초 안에 찾을 수 없는 경우 단일 대체 작업이 시간 초과됩니다. 예제를 성공적으로 실행하려면 리터럴 문자열 "MyMachine"을 로컬 컴퓨터 이름으로 바꿔야 합니다.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      // Get drives available on local computer and form into a single character expression.
      string[] drives = Environment.GetLogicalDrives();
      string driveNames = String.Empty;
      foreach (string drive in drives)
         driveNames += drive.Substring(0,1);
      // Create regular expression pattern dynamically based on local machine information.
      string pattern = @"\\\\" + Environment.MachineName + @"(?:\.\w+)*\\([" + driveNames + @"])\$";

      string replacement = "$1:";
      string[] uncPaths = { @"\\MyMachine.domain1.mycompany.com\C$\ThingsToDo.txt", 
                            @"\\MyMachine\c$\ThingsToDo.txt", 
                            @"\\MyMachine\d$\documents\mydocument.docx" }; 
      
      foreach (string uncPath in uncPaths)
      {
         Console.WriteLine("Input string: " + uncPath);
         string localPath = null;
         try {
            localPath = Regex.Replace(uncPath, pattern, replacement, 
                                      RegexOptions.IgnoreCase,
                                      TimeSpan.FromSeconds(0.5));
            Console.WriteLine("Returned string: " + localPath);
         }
         catch (RegexMatchTimeoutException) {
            Console.WriteLine("The replace operation timed out.");
            Console.WriteLine("Returned string: " + localPath);
            if (uncPath.Equals(localPath)) 
               Console.WriteLine("Equal to original path.");
            else
               Console.WriteLine("Original string: " + uncPath);
         }
         Console.WriteLine();
      }
   }
}
// The example displays the following output if run on a machine whose name is
// MyMachine:
//    Input string: \\MyMachine.domain1.mycompany.com\C$\ThingsToTo.txt
//    Returned string: C:\ThingsToDo.txt
//    
//    Input string: \\MyMachine\c$\ThingsToDo.txt
//    Returned string: c:\ThingsToDo.txt
//    
//    Input string: \\MyMachine\d$\documents\mydocument.docx
//    Returned string: d:\documents\mydocument.docx
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      ' Get drives available on local computer and form into a single character expression.
      Dim drives() As String = Environment.GetLogicalDrives()
      Dim driveNames As String = Nothing
      For Each drive As String In drives
         driveNames += drive.Substring(0,1)
      Next
      ' Create regular expression pattern dynamically based on local machine information.
      Dim pattern As String = "\\\\" + Environment.MachineName + "(?:\.\w+)*\\([" + driveNames + "])\$"

      Dim replacement As String = "$1:"
      Dim uncPaths() AS String = {"\\MyMachine.domain1.mycompany.com\C$\ThingsToDo.txt", _
                                  "\\MyMachine\c$\ThingsToDo.txt", _
                                  "\\MyMachine\d$\documents\mydocument.docx" } 
      
      For Each uncPath As String In uncPaths
         Console.WriteLine("Input string: " + uncPath)
         Dim localPath As String = Nothing
         Try
            localPath = Regex.Replace(uncPath, pattern, replacement, 
                                                               RegexOptions.IgnoreCase,
                                                               TimeSpan.FromSeconds(0.5))
            Console.WriteLine("Returned string: " + localPath)         
         Catch e As RegexMatchTimeoutException
            Console.WriteLine("The replace operation timed out.")
            Console.WriteLine("Returned string: " + localPath)
            If uncPath.Equals(localPath) Then 
               Console.WriteLine("Equal to original path.")
            Else
               Console.WriteLine("Original string: " + uncPath)
            End If
         End Try         
         Console.WriteLine()
      Next
   End Sub
End Module
' The example displays the following output if run on a machine whose name is
' MyMachine:
'    Input string: \\MyMachine.domain1.mycompany.com\C$\ThingsToTo.txt
'    Returned string: C:\ThingsToDo.txt
'    
'    Input string: \\MyMachine\c$\ThingsToDo.txt
'    Returned string: c:\ThingsToDo.txt
'    
'    Input string: \\MyMachine\d$\documents\mydocument.docx
'    Returned string: d:\documents\mydocument.docx

정규식 패턴은 다음 식으로 정의됩니다.

"\\\\" + Environment.MachineName + "(?:\.\w+)*\\([" + driveNames + "])\$"

다음 표에서는 정규식 패턴이 해석되는 방법을 보여 줍니다.

무늬 묘사
\\\\ 두 개의 연속 백슬래시(\) 문자를 일치합니다. 백슬래시 문자는 이스케이프 문자로 해석되므로 각 백슬래시는 다른 백슬래시로 이스케이프되어야 합니다.
+ Environment.MachineName + Environment.MachineName 속성에서 반환되는 문자열과 일치합니다.
(?:\.\w+)* 마침표(.) 문자 뒤에 하나 이상의 단어 문자를 찾습니다. 이 일치는 0회 이상 발생할 수 있습니다. 일치하는 하위 식이 캡처되지 않습니다.
\\ 백슬래시(\) 문자를 일치합니다.
([" + driveNames + "]) 개별 드라이브 문자로 구성된 문자 클래스와 일치합니다. 이 일치는 캡처된 첫 번째 하위 식입니다.
\$ 리터럴 달러 기호($) 문자와 일치합니다.

$1 대체 패턴은 전체 일치 항목을 캡처된 첫 번째 하위 식으로 바꿉니다. 즉, UNC 컴퓨터 및 드라이브 이름을 드라이브 문자로 바꿉니다.

설명

정적 Replace 메서드는 지정된 정규식 패턴을 사용하여 Regex 개체를 생성하고 인스턴스 메서드를 Replace호출하는 것과 같습니다.

pattern 매개 변수는 일치시킬 문자열을 상징적으로 설명하는 정규식 언어 요소로 구성됩니다. 정규식에 대한 자세한 내용은 .NET 정규식정규식 언어 - 빠른 참조참조하세요. options 매개 변수에 대한 RightToLeft 지정하면 입력 문자열의 끝에서 일치 항목 검색이 시작되고 왼쪽으로 이동합니다. 그렇지 않으면 입력 문자열의 시작 부분에 검색이 시작되고 오른쪽으로 이동합니다.

replacement 매개 변수는 input각 일치 항목을 바꿀 문자열을 지정합니다. replacement 리터럴 텍스트와 대체조합으로 구성 될 수 있습니다. 예를 들어 a*${test}b 대체 패턴은 문자열 "a*"를 삽입한 다음 test 캡처링 그룹과 일치하는 부분 문자열(있는 경우) 뒤에 문자열 "b"를 삽입합니다. * 문자는 대체 패턴 내에서 메타 문자로 인식되지 않습니다.

메모

대체는 대체 패턴에서 인식되는 유일한 정규식 언어 요소입니다. 문자 이스케이프를 비롯한 다른 모든 정규식 언어 요소는 정규식 패턴에서만 허용되며 대체 패턴에서는 인식되지 않습니다.

matchTimeout 매개 변수는 패턴 일치 메서드가 시간이 초과되기 전에 일치 항목을 찾으려고 시도하는 기간을 지정합니다. 제한 시간 간격을 설정하면 과도한 역추적에 의존하는 정규식이 가까운 일치 항목이 포함된 입력을 처리할 때 응답을 중지하는 것처럼 보이지 않습니다. 자세한 내용은 정규식 및 역추적대한 모범 사례를 참조하세요. 해당 시간 간격에 일치하는 항목이 없으면 메서드는 RegexMatchTimeoutException 예외를 throw합니다. matchTimeout 메서드가 실행되는 애플리케이션 도메인에 대해 정의된 기본 제한 시간 값을 재정의합니다.

일치하는 항목이 없으면 메서드가 변경되지 input 반환하므로 Object.ReferenceEquals 메서드를 사용하여 메서드가 입력 문자열을 대체했는지 여부를 확인할 수 있습니다.

호출자 참고

matchTimeout 매개 변수를 2초와 같은 적절한 값으로 설정하는 것이 좋습니다. InfiniteMatchTimeout지정하여 시간 초과를 사용하지 않도록 설정하면 정규식 엔진이 약간 더 나은 성능을 제공합니다. 그러나 다음 조건에서만 시간 초과를 사용하지 않도록 설정해야 합니다.

  • 정규식에서 처리된 입력이 알려진 신뢰할 수 있는 원본에서 파생되거나 정적 텍스트로 구성된 경우 사용자가 동적으로 입력한 텍스트는 제외됩니다.

  • 정규식 패턴을 철저히 테스트하여 일치 항목, 비 일치 항목 및 근사 일치 항목을 효율적으로 처리하는지 확인합니다.

  • 정규식 패턴에 거의 일치 항목을 처리할 때 과도한 역추적을 일으키는 것으로 알려진 언어 요소가 없는 경우

추가 정보

  • RegexOptions
  • 정규식 대체
  • 정규식 언어 요소
  • 정규식 역추적
  • .NET 정규식에 대한 모범 사례

적용 대상

Replace(String, String, String, RegexOptions)

Source:
Regex.Replace.cs
Source:
Regex.Replace.cs
Source:
Regex.Replace.cs

지정된 입력 문자열에서 지정된 정규식과 일치하는 모든 문자열을 지정된 대체 문자열로 대체합니다. 지정한 옵션은 일치 작업을 수정합니다.

public:
 static System::String ^ Replace(System::String ^ input, System::String ^ pattern, System::String ^ replacement, System::Text::RegularExpressions::RegexOptions options);
public static string Replace (string input, string pattern, string replacement, System.Text.RegularExpressions.RegexOptions options);
static member Replace : string * string * string * System.Text.RegularExpressions.RegexOptions -> string
Public Shared Function Replace (input As String, pattern As String, replacement As String, options As RegexOptions) As String

매개 변수

input
String

일치 항목을 검색할 문자열입니다.

pattern
String

일치시킬 정규식 패턴입니다.

replacement
String

대체 문자열입니다.

options
RegexOptions

일치 옵션을 제공하는 열거형 값의 비트 조합입니다.

반환

대체 문자열이 일치하는 각 문자열을 대신한다는 점을 제외하고 입력 문자열과 동일한 새 문자열입니다. 현재 인스턴스에서 pattern 일치하지 않으면 메서드는 변경되지 않은 현재 인스턴스를 반환합니다.

예외

정규식 구문 분석 오류가 발생했습니다.

input, pattern또는 replacementnull.

options RegexOptions 값의 유효한 비트 조합이 아닙니다.

시간 초과가 발생했습니다. 제한 시간에 대한 자세한 내용은 주의 섹션을 참조하세요.

예제

다음 예제에서는 Replace(String, String, String, RegexOptions) 메서드를 사용하여 UNC 경로의 로컬 컴퓨터 및 드라이브 이름을 로컬 파일 경로로 바꿉니다. 정규식은 Environment.MachineName 속성을 사용하여 로컬 컴퓨터의 이름과 논리 드라이브의 이름을 포함하는 Environment.GetLogicalDrives 메서드를 포함합니다. 모든 정규식 문자열 비교는 대/소문자를 구분하지 않습니다. 예제를 성공적으로 실행하려면 리터럴 문자열 "MyMachine"을 로컬 컴퓨터 이름으로 바꿔야 합니다.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      // Get drives available on local computer and form into a single character expression.
      string[] drives = Environment.GetLogicalDrives();
      string driveNames = String.Empty;
      foreach (string drive in drives)
         driveNames += drive.Substring(0,1);
      // Create regular expression pattern dynamically based on local machine information.
      string pattern = @"\\\\" + Environment.MachineName + @"(?:\.\w+)*\\([" + driveNames + @"])\$";

      string replacement = "$1:";
      string[] uncPaths = { @"\\MyMachine.domain1.mycompany.com\C$\ThingsToDo.txt", 
                            @"\\MyMachine\c$\ThingsToDo.txt", 
                            @"\\MyMachine\d$\documents\mydocument.docx" }; 
      
      foreach (string uncPath in uncPaths)
      {
         Console.WriteLine("Input string: " + uncPath);
         Console.WriteLine("Returned string: " + Regex.Replace(uncPath, pattern, replacement, RegexOptions.IgnoreCase));
         Console.WriteLine();
      }
   }
}
// The example displays the following output if run on a machine whose name is
// MyMachine:
//    Input string: \\MyMachine.domain1.mycompany.com\C$\ThingsToTo.txt
//    Returned string: C:\ThingsToDo.txt
//    
//    Input string: \\MyMachine\c$\ThingsToDo.txt
//    Returned string: c:\ThingsToDo.txt
//    
//    Input string: \\MyMachine\d$\documents\mydocument.docx
//    Returned string: d:\documents\mydocument.docx
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      ' Get drives available on local computer and form into a single character expression.
      Dim drives() As String = Environment.GetLogicalDrives()
      Dim driveNames As String = Nothing
      For Each drive As String In drives
         driveNames += drive.Substring(0,1)
      Next
      ' Create regular expression pattern dynamically based on local machine information.
      Dim pattern As String = "\\\\" + Environment.MachineName + "(?:\.\w+)*\\([" + driveNames + "])\$"

      Dim replacement As String = "$1:"
      Dim uncPaths() AS String = {"\\MyMachine.domain1.mycompany.com\C$\ThingsToDo.txt", _
                                  "\\MyMachine\c$\ThingsToDo.txt", _
                                  "\\MyMachine\d$\documents\mydocument.docx" } 
      
      For Each uncPath As String In uncPaths
         Console.WriteLine("Input string: " + uncPath)
         Console.WriteLine("Returned string: " + Regex.Replace(uncPath, pattern, replacement, RegexOptions.IgnoreCase))
         Console.WriteLine()
      Next
   End Sub
End Module
' The example displays the following output if run on a machine whose name is
' MyMachine:
'    Input string: \\MyMachine.domain1.mycompany.com\C$\ThingsToTo.txt
'    Returned string: C:\ThingsToDo.txt
'    
'    Input string: \\MyMachine\c$\ThingsToDo.txt
'    Returned string: c:\ThingsToDo.txt
'    
'    Input string: \\MyMachine\d$\documents\mydocument.docx
'    Returned string: d:\documents\mydocument.docx

정규식 패턴은 다음 식으로 정의됩니다.

"\\\\" + Environment.MachineName + "(?:\.\w+)*\\([" + driveNames + "])\$"

다음 표에서는 정규식 패턴이 해석되는 방법을 보여 줍니다.

무늬 묘사
\\\\ 두 개의 연속 백슬래시(\) 문자를 일치합니다. 백슬래시 문자는 이스케이프 문자로 해석되므로 각 백슬래시는 다른 백슬래시로 이스케이프되어야 합니다.
+ Environment.MachineName + Environment.MachineName 속성에서 반환되는 문자열과 일치합니다.
(?:\.\w+)* 마침표(.) 문자 뒤에 하나 이상의 단어 문자를 찾습니다. 이 일치는 0회 이상 발생할 수 있습니다. 일치하는 하위 식이 캡처되지 않습니다.
\\ 백슬래시(\) 문자를 일치합니다.
([" + driveNames + "]) 개별 드라이브 문자로 구성된 문자 클래스와 일치합니다. 이 일치는 캡처된 첫 번째 하위 식입니다.
\$ 리터럴 달러 기호($) 문자와 일치합니다.

$1 대체 패턴은 전체 일치 항목을 캡처된 첫 번째 하위 식으로 바꿉니다. 즉, UNC 컴퓨터 및 드라이브 이름을 드라이브 문자로 바꿉니다.

설명

정적 Replace 메서드는 지정된 정규식 패턴을 사용하여 Regex 개체를 생성하고 인스턴스 메서드를 Replace호출하는 것과 같습니다.

pattern 매개 변수는 일치시킬 문자열을 상징적으로 설명하는 정규식 언어 요소로 구성됩니다. 정규식에 대한 자세한 내용은 .NET 정규식정규식 언어 - 빠른 참조참조하세요. options 매개 변수에 대한 RightToLeft 지정하면 입력 문자열의 끝에서 일치 항목 검색이 시작되고 왼쪽으로 이동합니다. 그렇지 않으면 입력 문자열의 시작 부분에 검색이 시작되고 오른쪽으로 이동합니다.

replacement 매개 변수는 input각 일치 항목을 바꿀 문자열을 지정합니다. replacement 리터럴 텍스트와 대체조합으로 구성 될 수 있습니다. 예를 들어 a*${test}b 대체 패턴은 문자열 "a*"를 삽입한 다음 test 캡처링 그룹과 일치하는 부분 문자열(있는 경우) 뒤에 문자열 "b"를 삽입합니다. * 문자는 대체 패턴 내에서 메타 문자로 인식되지 않습니다.

메모

대체는 대체 패턴에서 인식되는 유일한 정규식 언어 요소입니다. 문자 이스케이프를 비롯한 다른 모든 정규식 언어 요소는 정규식 패턴에서만 허용되며 대체 패턴에서는 인식되지 않습니다.

대체 작업의 실행 시간이 메서드가 호출되는 애플리케이션 도메인에 대해 지정된 제한 시간 간격을 초과하면 RegexMatchTimeoutException 예외가 throw됩니다. 애플리케이션 도메인의 속성에 제한 시간이 정의되어 있지 않거나 시간 제한 값이 Regex.InfiniteMatchTimeout경우 예외가 throw되지 않습니다.

일치하는 항목이 없으면 메서드가 변경되지 input 반환하므로 Object.ReferenceEquals 메서드를 사용하여 메서드가 입력 문자열을 대체했는지 여부를 확인할 수 있습니다.

호출자 참고

이 메서드는 호출되는 애플리케이션 도메인의 기본 제한 시간 값과 동일한 간격 후에 시간 초과됩니다. 애플리케이션 도메인에 대해 제한 시간 값이 정의되지 않은 경우 메서드의 시간 초과를 방지하는 InfiniteMatchTimeout값이 사용됩니다. 패턴 일치를 바꾸는 데 권장되는 정적 메서드는 Replace(String, String, String, RegexOptions, TimeSpan)제한 시간 간격을 설정할 수 있습니다.

추가 정보

적용 대상

Replace(String, MatchEvaluator)

Source:
Regex.Replace.cs
Source:
Regex.Replace.cs
Source:
Regex.Replace.cs

지정된 입력 문자열에서 지정된 정규식과 일치하는 모든 문자열을 MatchEvaluator 대리자가 반환한 문자열로 대체합니다.

public:
 System::String ^ Replace(System::String ^ input, System::Text::RegularExpressions::MatchEvaluator ^ evaluator);
public string Replace (string input, System.Text.RegularExpressions.MatchEvaluator evaluator);
member this.Replace : string * System.Text.RegularExpressions.MatchEvaluator -> string
Public Function Replace (input As String, evaluator As MatchEvaluator) As String

매개 변수

input
String

일치 항목을 검색할 문자열입니다.

evaluator
MatchEvaluator

각 일치 항목을 검사하고 일치하는 원래 문자열 또는 대체 문자열을 반환하는 사용자 지정 메서드입니다.

반환

대체 문자열이 일치하는 각 문자열을 대신한다는 점을 제외하고 입력 문자열과 동일한 새 문자열입니다. 정규식 패턴이 현재 인스턴스에서 일치하지 않으면 메서드는 변경되지 않은 현재 인스턴스를 반환합니다.

예외

input 또는 evaluatornull.

시간 초과가 발생했습니다. 제한 시간에 대한 자세한 내용은 주의 섹션을 참조하세요.

예제

다음 코드 예제에서는 원래 문자열을 표시하고, 원래 문자열의 각 단어와 일치하고, 각 일치 항목의 첫 번째 문자를 대문자로 변환한 다음, 변환된 문자열을 표시합니다.

using System;
using System.Text.RegularExpressions;

class RegExSample
{
    static string CapText(Match m)
    {
        // Get the matched string.
        string x = m.ToString();
        // If the first char is lower case...
        if (char.IsLower(x[0]))
        {
            // Capitalize it.
            return char.ToUpper(x[0]) + x.Substring(1, x.Length - 1);
        }
        return x;
    }

    static void Main()
    {
        string text = "four score and seven years ago";

        Console.WriteLine($"text=[{text}]");

        Regex rx = new Regex(@"\w+");

        string result = rx.Replace(text, new MatchEvaluator(RegExSample.CapText));

        Console.WriteLine($"result=[{result}]");
    }
}
// The example displays the following output:
//       text=[four score and seven years ago]
//       result=[Four Score And Seven Years Ago]
Imports System.Text.RegularExpressions

Module RegExSample
    Function CapText(ByVal m As Match) As String
        ' Get the matched string.
        Dim x As String = m.ToString()
        ' If the first char is lower case...
        If Char.IsLower(x.Chars(0)) Then
            ' Capitalize it.
            Return Char.ToUpper(x.Chars(0)) & x.Substring(1, x.Length - 1)
        End If
        Return x
    End Function

    Sub Main()
        Dim text As String = "four score and seven years ago"

        Console.WriteLine($"text=[{text}]")

        Dim rx As New Regex("\w+")

        Dim result As String = rx.Replace(text, AddressOf RegExSample.CapText)

        Console.WriteLine($"result=[{result}]")
    End Sub
End Module
' The example displays the following output:
'       text=[four score and seven years ago]
'       result=[Four Score And Seven Years Ago]

설명

Regex.Replace(String, MatchEvaluator) 메서드는 다음 조건 중 하나라도 충족되는 경우 정규식 일치를 바꾸는 데 유용합니다.

  • 정규식 대체 패턴으로 대체 문자열을 쉽게 지정할 수 없습니다.

  • 대체 문자열은 일치하는 문자열에서 수행된 일부 처리로 인해 발생합니다.

  • 대체 문자열은 조건부 처리로 인해 발생합니다.

이 메서드는 Regex.Matches(String) 메서드를 호출하고 반환된 MatchCollection 컬렉션의 각 Match 개체를 evaluator 대리자에게 전달하는 것과 같습니다.

정규식은 현재 Regex 개체에 대한 생성자가 정의한 패턴입니다.

evaluator 매개 변수는 사용자가 정의하고 각 일치 항목을 검사하는 사용자 지정 메서드의 대리자입니다. MatchEvaluator 대리자를 일치하려면 사용자 지정 메서드에 다음 서명이 있어야 합니다.

public string MatchEvaluatorMethod(Match match)
Public Function MatchEvaluatorMethod(match As Match) As String

사용자 지정 메서드는 일치하는 입력을 대체하는 문자열을 반환합니다.

대체 작업의 실행 시간이 Regex.Regex(String, RegexOptions, TimeSpan) 생성자가 지정한 제한 시간 간격을 초과하면 RegexMatchTimeoutException 예외가 throw됩니다. 생성자를 호출할 때 제한 시간 간격을 설정하지 않으면 작업이 Regex 개체가 만들어진 애플리케이션 도메인에 대해 설정된 제한 시간 값을 초과하면 예외가 throw됩니다. Regex 생성자 호출 또는 애플리케이션 도메인의 속성에 제한 시간이 정의되지 않거나 제한 시간 값이 Regex.InfiniteMatchTimeout경우 예외가 throw되지 않습니다.

일치하는 항목이 없으면 메서드가 변경되지 input 반환하므로 Object.ReferenceEquals 메서드를 사용하여 메서드가 입력 문자열을 대체했는지 여부를 확인할 수 있습니다.

추가 정보

적용 대상

Replace(String, MatchEvaluator, Int32)

Source:
Regex.Replace.cs
Source:
Regex.Replace.cs
Source:
Regex.Replace.cs

지정된 입력 문자열에서 정규식 패턴과 일치하는 지정된 최대 문자열 수를 MatchEvaluator 대리자가 반환한 문자열로 대체합니다.

public:
 System::String ^ Replace(System::String ^ input, System::Text::RegularExpressions::MatchEvaluator ^ evaluator, int count);
public string Replace (string input, System.Text.RegularExpressions.MatchEvaluator evaluator, int count);
member this.Replace : string * System.Text.RegularExpressions.MatchEvaluator * int -> string
Public Function Replace (input As String, evaluator As MatchEvaluator, count As Integer) As String

매개 변수

input
String

일치 항목을 검색할 문자열입니다.

evaluator
MatchEvaluator

각 일치 항목을 검사하고 일치하는 원래 문자열 또는 대체 문자열을 반환하는 사용자 지정 메서드입니다.

count
Int32

교체가 발생하는 최대 횟수입니다.

반환

대체 문자열이 일치하는 각 문자열을 대신한다는 점을 제외하고 입력 문자열과 동일한 새 문자열입니다. 정규식 패턴이 현재 인스턴스에서 일치하지 않으면 메서드는 변경되지 않은 현재 인스턴스를 반환합니다.

예외

input 또는 evaluatornull.

시간 초과가 발생했습니다. 제한 시간에 대한 자세한 내용은 주의 섹션을 참조하세요.

예제

다음 예제에서는 정규식을 사용하여 목록에서 단어의 절반을 의도적으로 잘못 입력합니다. 정규식 \w*(ie|ei)\w* 사용하여 "ie" 또는 "ei" 문자를 포함하는 단어와 일치합니다. 일치하는 단어의 전반부를 ReverseLetter 메서드에 전달합니다. 이 메서드는 Replace(String, String, String, RegexOptions) 메서드를 사용하여 일치하는 문자열에서 "i" 및 "e"를 반대로 바뀝니다. 나머지 단어는 변경되지 않은 상태로 유지됩니다.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string input = "deceive relieve achieve belief fierce receive";
      string pattern = @"\w*(ie|ei)\w*";
      Regex rgx = new Regex(pattern, RegexOptions.IgnoreCase);
      Console.WriteLine("Original string: " + input);
      
      string result = rgx.Replace(input, new MatchEvaluator(Example.ReverseLetter), 
                                  input.Split(' ').Length / 2);
      Console.WriteLine("Returned string: " + result);
   }

   static string ReverseLetter(Match match)
   {
      return Regex.Replace(match.Value, "([ie])([ie])", "$2$1", 
                           RegexOptions.IgnoreCase);            
   }
}
// The example displays the following output:
//    Original string: deceive relieve achieve belief fierce receive
//    Returned string: decieve releive acheive belief fierce receive
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim input As String = "deceive relieve achieve belief fierce receive"
      Dim pattern As String = "\w*(ie|ei)\w*"
      Dim rgx As New Regex(pattern, RegexOptions.IgnoreCase)
      Console.WriteLine("Original string: " + input)
      
      Dim result As String = rgx.Replace(input, AddressOf ReverseLetter, 
                                           input.Split(" "c).Length \ 2)
      Console.WriteLine("Returned string: " + result)
   End Sub

   Public Function ReverseLetter(match As Match) As String
      Return Regex.Replace(match.Value, "([ie])([ie])", "$2$1", 
                           RegexOptions.IgnoreCase)            
   End Function
End Module
' The example displays the following output:
'    Original string: deceive relieve achieve belief fierce receive
'    Returned string: decieve releive acheive belief fierce receive

\w*(ie|ei)\w* 정규식은 다음 표와 같이 정의됩니다.

무늬 묘사
\w* 0개 이상의 단어 문자를 찾습니다.
(ie|ei) "ie" 또는 "ei"와 일치합니다.
\w* 0개 이상의 단어 문자를 찾습니다.

ReverseLetter 메서드에서 ([ie])([ie]) 정규식 패턴은 diphthong "ie" 또는 "ei"의 첫 번째 "i" 또는 "e"와 일치하고 첫 번째 캡처링 그룹에 문자를 할당합니다. 두 번째 "i" 또는 "e"와 일치하고 두 번째 캡처 그룹에 문자를 할당합니다. 그런 다음 두 문자는 대체 패턴 $2$1Replace(String, String, String) 메서드를 호출하여 반대로 바뀝니다.

설명

Regex.Replace(String, MatchEvaluator, Int32) 메서드는 다음 조건 중 하나라도 충족되는 경우 정규식 일치를 바꾸는 데 유용합니다.

  • 정규식 대체 패턴으로 대체 문자열을 쉽게 지정할 수 없습니다.

  • 대체 문자열은 일치하는 문자열에서 수행된 일부 처리로 인해 발생합니다.

  • 대체 문자열은 조건부 처리로 인해 발생합니다.

이 메서드는 Regex.Matches(String) 메서드를 호출하고 반환된 MatchCollection 컬렉션의 첫 번째 countMatch 개체를 evaluator 대리자에게 전달하는 것과 같습니다.

정규식은 현재 Regex 개체에 대한 생성자가 정의한 패턴입니다.

evaluator 매개 변수는 사용자가 정의하고 각 일치 항목을 검사하는 사용자 지정 메서드의 대리자입니다. MatchEvaluator 대리자를 일치하려면 사용자 지정 메서드에 다음 서명이 있어야 합니다.

public string MatchEvaluatorMethod(Match match)
Public Function MatchEvaluatorMethod(match As Match) As String

사용자 지정 메서드는 일치하는 입력을 대체하는 문자열을 반환합니다.

대체 작업의 실행 시간이 Regex.Regex(String, RegexOptions, TimeSpan) 생성자가 지정한 제한 시간 간격을 초과하면 RegexMatchTimeoutException 예외가 throw됩니다. 생성자를 호출할 때 제한 시간 간격을 설정하지 않으면 작업이 Regex 개체가 만들어진 애플리케이션 도메인에 대해 설정된 제한 시간 값을 초과하면 예외가 throw됩니다. Regex 생성자 호출 또는 애플리케이션 도메인의 속성에 제한 시간이 정의되지 않거나 제한 시간 값이 Regex.InfiniteMatchTimeout경우 예외가 throw되지 않습니다.

일치하는 항목이 없으면 메서드가 변경되지 input 반환하므로 Object.ReferenceEquals 메서드를 사용하여 메서드가 입력 문자열을 대체했는지 여부를 확인할 수 있습니다.

추가 정보

적용 대상

Replace(String, String, MatchEvaluator)

Source:
Regex.Replace.cs
Source:
Regex.Replace.cs
Source:
Regex.Replace.cs

지정된 입력 문자열에서 지정된 정규식과 일치하는 모든 문자열을 MatchEvaluator 대리자가 반환한 문자열로 대체합니다.

public:
 static System::String ^ Replace(System::String ^ input, System::String ^ pattern, System::Text::RegularExpressions::MatchEvaluator ^ evaluator);
public static string Replace (string input, string pattern, System.Text.RegularExpressions.MatchEvaluator evaluator);
static member Replace : string * string * System.Text.RegularExpressions.MatchEvaluator -> string
Public Shared Function Replace (input As String, pattern As String, evaluator As MatchEvaluator) As String

매개 변수

input
String

일치 항목을 검색할 문자열입니다.

pattern
String

일치시킬 정규식 패턴입니다.

evaluator
MatchEvaluator

각 일치 항목을 검사하고 일치하는 원래 문자열 또는 대체 문자열을 반환하는 사용자 지정 메서드입니다.

반환

대체 문자열이 일치하는 각 문자열을 대신한다는 점을 제외하고 입력 문자열과 동일한 새 문자열입니다. 현재 인스턴스에서 pattern 일치하지 않으면 메서드는 변경되지 않은 현재 인스턴스를 반환합니다.

예외

정규식 구문 분석 오류가 발생했습니다.

input, pattern또는 evaluatornull.

시간 초과가 발생했습니다. 제한 시간에 대한 자세한 내용은 주의 섹션을 참조하세요.

예제

다음 예제에서는 정규식을 사용하여 문자열에서 개별 단어를 추출한 다음 MatchEvaluator 대리자를 사용하여 단어의 개별 문자를 스크램블링하는 WordScramble 메서드를 호출합니다. 이를 위해 WordScramble 메서드는 일치 항목의 문자를 포함하는 배열을 만듭니다. 또한 임의 부동 소수점 숫자로 채우는 병렬 배열을 만듭니다. 배열은 Array.Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>) 메서드를 호출하여 정렬되고 정렬된 배열은 String 클래스 생성자에 대한 인수로 제공됩니다. 새로 만든 이 문자열은 WordScramble 메서드에서 반환됩니다. 정규식 패턴 \w+ 하나 이상의 단어 문자와 일치합니다. 정규식 엔진은 공백 문자와 같은 단어가 아닌 문자를 발견할 때까지 일치 항목에 문자를 계속 추가합니다.

using System;
using System.Collections;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string words = "letter alphabetical missing lack release " + 
                     "penchant slack acryllic laundry cease";
      string pattern = @"\w+";                            
      MatchEvaluator evaluator = new MatchEvaluator(WordScrambler);
      Console.WriteLine("Original words:");
      Console.WriteLine(words);
      Console.WriteLine();
      Console.WriteLine("Scrambled words:");
      Console.WriteLine(Regex.Replace(words, pattern, evaluator));      
   }

   public static string WordScrambler(Match match)
   {
      int arraySize = match.Value.Length;
      // Define two arrays equal to the number of letters in the match.
      double[] keys = new double[arraySize];
      char[] letters = new char[arraySize];
      
      // Instantiate random number generator'
      Random rnd = new Random();
      
      for (int ctr = 0; ctr < match.Value.Length; ctr++)
      {
         // Populate the array of keys with random numbers.
         keys[ctr] = rnd.NextDouble();
         // Assign letter to array of letters.
         letters[ctr] = match.Value[ctr];
      }         
      Array.Sort(keys, letters, 0, arraySize, Comparer.Default);      
      return new String(letters);
   }
}
// The example displays output similar to the following:
//    Original words:
//    letter alphabetical missing lack release penchant slack acryllic laundry cease
//    
//    Scrambled words:
//    elrtte iaeabatlpchl igmnssi lcka aerslee hnpatnce ksacl lialcryc dylruna ecase
Imports System.Collections
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim words As String = "letter alphabetical missing lack release " + _
                            "penchant slack acryllic laundry cease"
      Dim pattern As String = "\w+"                            
      Dim evaluator As MatchEvaluator = AddressOf WordScrambler
      Console.WriteLine("Original words:")
      Console.WriteLine(words)
      Console.WriteLine("Scrambled words:")
      Console.WriteLine(Regex.Replace(words, pattern, evaluator))      
   End Sub
   
   Public Function WordScrambler(match As Match) As String
      Dim arraySize As Integer = match.Value.Length - 1
      ' Define two arrays equal to the number of letters in the match.
      Dim keys(arraySize) As Double
      Dim letters(arraySize) As Char
      
      ' Instantiate random number generator'
      Dim rnd As New Random()
      
      For ctr As Integer = 0 To match.Value.Length - 1
         ' Populate the array of keys with random numbers.
         keys(ctr) = rnd.NextDouble()
         ' Assign letter to array of letters.
         letters(ctr) = match.Value.Chars(ctr)
      Next         
      Array.Sort(keys, letters, 0, arraySize, Comparer.Default)      
      Return New String(letters)
   End Function
End Module
' The example displays output similar to the following:
'    Original words:
'    letter alphabetical missing lack release penchant slack acryllic laundry cease
'    
'    Scrambled words:
'    elrtte iaeabatlpchl igmnssi lcka aerslee hnpatnce ksacl lialcryc dylruna ecase

설명

Regex.Replace(String, String, MatchEvaluator) 메서드는 다음 조건 중 하나라도 충족되는 경우 정규식 일치를 바꾸는 데 유용합니다.

  • 정규식 대체 패턴으로 대체 문자열을 쉽게 지정할 수 없습니다.

  • 대체 문자열은 일치하는 문자열에서 수행된 일부 처리로 인해 발생합니다.

  • 대체 문자열은 조건부 처리로 인해 발생합니다.

이 메서드는 Regex.Matches(String, String) 메서드를 호출하고 반환된 MatchCollection 컬렉션의 각 Match 개체를 evaluator 대리자에게 전달하는 것과 같습니다.

pattern 매개 변수는 일치시킬 문자열을 상징적으로 설명하는 정규식 언어 요소로 구성됩니다. 정규식에 대한 자세한 내용은 .NET 정규식정규식 언어 - 빠른 참조참조하세요.

evaluator 매개 변수는 사용자가 정의하고 각 일치 항목을 검사하는 사용자 지정 메서드의 대리자입니다. MatchEvaluator 대리자를 일치하려면 사용자 지정 메서드에 다음 서명이 있어야 합니다.

public string MatchEvaluatorMethod(Match match)
Public Function MatchEvaluatorMethod(match As Match) As String

사용자 지정 메서드는 일치하는 입력을 대체하는 문자열을 반환합니다.

대체 작업의 실행 시간이 메서드가 호출되는 애플리케이션 도메인에 대해 지정된 제한 시간 간격을 초과하면 RegexMatchTimeoutException 예외가 throw됩니다. 애플리케이션 도메인의 속성에 제한 시간이 정의되어 있지 않거나 시간 제한 값이 Regex.InfiniteMatchTimeout경우 예외가 throw되지 않습니다.

일치하는 항목이 없으면 메서드가 변경되지 input 반환하므로 Object.ReferenceEquals 메서드를 사용하여 메서드가 입력 문자열을 대체했는지 여부를 확인할 수 있습니다.

호출자 참고

이 메서드는 호출되는 애플리케이션 도메인의 기본 제한 시간 값과 동일한 간격 후에 시간 초과됩니다. 애플리케이션 도메인에 대해 제한 시간 값이 정의되지 않은 경우 메서드의 시간 초과를 방지하는 InfiniteMatchTimeout값이 사용됩니다. 패턴 일치를 평가하고 바꾸기 위해 권장되는 정적 메서드는 Replace(String, String, MatchEvaluator, RegexOptions, TimeSpan)제한 시간 간격을 설정할 수 있습니다.

추가 정보

적용 대상

Replace(String, String, Int32)

Source:
Regex.Replace.cs
Source:
Regex.Replace.cs
Source:
Regex.Replace.cs

지정된 입력 문자열에서 정규식 패턴과 일치하는 지정된 최대 문자열 수를 지정된 대체 문자열로 대체합니다.

public:
 System::String ^ Replace(System::String ^ input, System::String ^ replacement, int count);
public string Replace (string input, string replacement, int count);
member this.Replace : string * string * int -> string
Public Function Replace (input As String, replacement As String, count As Integer) As String

매개 변수

input
String

일치 항목을 검색할 문자열입니다.

replacement
String

대체 문자열입니다.

count
Int32

교체가 발생할 수 있는 최대 횟수입니다.

반환

대체 문자열이 일치하는 각 문자열을 대신한다는 점을 제외하고 입력 문자열과 동일한 새 문자열입니다. 정규식 패턴이 현재 인스턴스에서 일치하지 않으면 메서드는 변경되지 않은 현재 인스턴스를 반환합니다.

예외

input 또는 replacementnull.

시간 초과가 발생했습니다. 제한 시간에 대한 자세한 내용은 주의 섹션을 참조하세요.

예제

다음 예제에서는 중복된 문자의 처음 5개 항목을 단일 문자로 바꿉니다. 정규식 패턴 (\w)\1 단일 문자의 연속 발생과 일치하고 첫 번째 캡처링 그룹에 첫 번째 항목을 할당합니다. $1 대체 패턴은 전체 일치 항목을 캡처된 첫 번째 그룹으로 바꿉니다.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string str = "aabccdeefgghiijkklmm";
      string pattern = "(\\w)\\1"; 
      string replacement = "$1"; 
      Regex rgx = new Regex(pattern);

      string result = rgx.Replace(str, replacement, 5);
      Console.WriteLine("Original String:    '{0}'", str);
      Console.WriteLine("Replacement String: '{0}'", result); 
   }
}
// The example displays the following output:
//       Original String:    'aabccdeefgghiijkklmm'
//       Replacement String: 'abcdefghijkklmm'
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim str As String = "aabccdeefgghiijkklmm"
      Dim pattern As String = "(\w)\1" 
      Dim replacement As String = "$1" 
      Dim rgx As New Regex(pattern)

      Dim result As String = rgx.Replace(str, replacement, 5)
      Console.WriteLine("Original String:    '{0}'", str)
      Console.WriteLine("Replacement String: '{0}'", result)                             
   End Sub
End Module
' The example displays the following output:
'       Original String:    'aabccdeefgghiijkklmm'
'       Replacement String: 'abcdefghijkklmm'

설명

일치 항목 검색은 input 문자열의 시작 부분에서 시작됩니다. 정규식은 현재 Regex 개체의 생성자에 의해 정의된 패턴입니다. count 음수이면 대체 항목이 문자열의 끝으로 계속 바꿉니다. count 일치 항목 수를 초과하면 모든 일치 항목이 바뀝니다.

replacement 매개 변수는 input첫 번째 count 일치 항목을 바꿀 문자열을 지정합니다. replacement 리터럴 텍스트와 대체조합으로 구성 될 수 있습니다. 예를 들어 a*${test}b 대체 패턴은 문자열 "a*"를 삽입한 다음 test 캡처링 그룹과 일치하는 부분 문자열(있는 경우) 뒤에 문자열 "b"를 삽입합니다. * 문자는 대체 패턴 내에서 메타 문자로 인식되지 않습니다.

메모

대체는 대체 패턴에서 인식되는 유일한 정규식 언어 요소입니다. 문자 이스케이프를 비롯한 다른 모든 정규식 언어 요소는 정규식 패턴에서만 허용되며 대체 패턴에서는 인식되지 않습니다.

대체 작업의 실행 시간이 Regex.Regex(String, RegexOptions, TimeSpan) 생성자가 지정한 제한 시간 간격을 초과하면 RegexMatchTimeoutException 예외가 throw됩니다. 생성자를 호출할 때 제한 시간 간격을 설정하지 않으면 작업이 Regex 개체가 만들어진 애플리케이션 도메인에 대해 설정된 제한 시간 값을 초과하면 예외가 throw됩니다. Regex 생성자 호출 또는 애플리케이션 도메인의 속성에 제한 시간이 정의되지 않거나 제한 시간 값이 Regex.InfiniteMatchTimeout경우 예외가 throw되지 않습니다.

일치하는 항목이 없으면 메서드가 변경되지 input 반환하므로 Object.ReferenceEquals 메서드를 사용하여 메서드가 입력 문자열을 대체했는지 여부를 확인할 수 있습니다.

추가 정보

적용 대상

Replace(String, String)

Source:
Regex.Replace.cs
Source:
Regex.Replace.cs
Source:
Regex.Replace.cs

지정된 입력 문자열에서 정규식 패턴과 일치하는 모든 문자열을 지정된 대체 문자열로 대체합니다.

public:
 System::String ^ Replace(System::String ^ input, System::String ^ replacement);
public string Replace (string input, string replacement);
member this.Replace : string * string -> string
Public Function Replace (input As String, replacement As String) As String

매개 변수

input
String

일치 항목을 검색할 문자열입니다.

replacement
String

대체 문자열입니다.

반환

대체 문자열이 일치하는 각 문자열을 대신한다는 점을 제외하고 입력 문자열과 동일한 새 문자열입니다. 정규식 패턴이 현재 인스턴스에서 일치하지 않으면 메서드는 변경되지 않은 현재 인스턴스를 반환합니다.

예외

input 또는 replacementnull.

시간 초과가 발생했습니다. 제한 시간에 대한 자세한 내용은 주의 섹션을 참조하세요.

예제

다음 예제에서는 하나 이상의 공백 문자와 일치하는 정규식 \s+정의합니다. 대체 문자열 "은 단일 공백 문자로 바꿉니다.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string input = "This is   text with   far  too   much   " + 
                     "white space.";
      string pattern = "\\s+";
      string replacement = " ";
      Regex rgx = new Regex(pattern);
      string result = rgx.Replace(input, replacement);
      
      Console.WriteLine("Original String: {0}", input);
      Console.WriteLine("Replacement String: {0}", result);                             
   }
}
// The example displays the following output:
//       Original String: This is   text with   far  too   much   white space.
//       Replacement String: This is text with far too much white space.
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim input As String = "This is   text with   far  too   much   " + _
                            "white space."
      Dim pattern As String = "\s+"
      Dim replacement As String = " "
      Dim rgx As New Regex(pattern)
      Dim result As String = rgx.Replace(input, replacement)
      
      Console.WriteLine("Original String: {0}", input)
      Console.WriteLine("Replacement String: {0}", result)                             
   End Sub
End Module
' The example displays the following output:
'          Original String: This is   text with   far  too   much   white space.
'          Replacement String: This is text with far too much white space.

다음 예제에서는 숫자 값에서 선행 또는 후행 통화 기호를 제거하는 정규식, (\p{Sc}\s?)?(\d+\.?((?<=\.)\d+)?)(?(1)|\s?\p{Sc})?및 대체 패턴($2)을 정의합니다.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string pattern =  @"(\p{Sc}\s?)?(\d+\.?((?<=\.)\d+)?)(?(1)|\s?\p{Sc})?";
      string input = "$17.43  €2 16.33  £0.98  0.43   £43   12€  17";
      string replacement = "$2";
      Regex rgx = new Regex(pattern);
      string result = rgx.Replace(input, replacement);

      Console.WriteLine("Original String:    '{0}'", input);
      Console.WriteLine("Replacement String: '{0}'", result);                             
   }
}
// The example displays the following output:
//       Original String:    '$17.43  €2 16.33  £0.98  0.43   £43   12€  17'
//       Replacement String: '17.43  2 16.33  0.98  0.43   43   12  17'
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim pattern As String =  "(\p{Sc}\s?)?(\d+\.?((?<=\.)\d+)?)(?(1)|\s?\p{Sc})?"
      Dim input As String = "$17.43  €2 16.33  £0.98  0.43   £43   12€  17"
      Dim replacement As String = "$2"
      Dim rgx As New Regex(pattern)
      Dim result As String = rgx.Replace(input, replacement)

      Console.WriteLine("Original String:    '{0}'", input)
      Console.WriteLine("Replacement String: '{0}'", result)                             
   End Sub
End Module
' The example displays the following output:
'       Original String:    '$17.43  €2 16.33  £0.98  0.43   £43   12€  17'
'       Replacement String: '17.43  2 16.33  0.98  0.43   43   12  17'

정규식은 다음 표와 같이 해석됩니다.

무늬 묘사
\p{Sc} 통화 기호와 일치합니다. {Sc} 유니코드 기호, 통화 범주의 멤버인 문자를 표시합니다.
\s? 0개 또는 1개의 공백 문자를 찾습니다.
(\p{Sc}\s?)? 통화 기호 조합의 0개 또는 1개와 0개 또는 1개의 공백 문자를 찾습니다. 첫 번째 캡처링 그룹입니다.
\d+ 하나 이상의 10진수를 찾습니다.
\.? 마침표가 0개 또는 1개(소수 구분 기호 문자로 사용됨)와 일치합니다.
((?<=\.)\d+)? 마침표가 이전 문자인 경우 하나 이상의 소수 자릿수를 일치시킵니다. 이 패턴은 0 또는 한 번 일치시킬 수 있습니다.
(\d+\.?((?<=\.)\d+)?) 하나 이상의 10진수 패턴과 선택적 마침표 및 추가 소수 자릿수를 찾습니다. 두 번째 캡처링 그룹입니다. Replace(String, String) 메서드에 대한 호출은 전체 일치 항목을 캡처된 그룹의 값으로 바꿉니다.
(?(1)|\s?\p{Sc})? 캡처된 첫 번째 그룹이 있는 경우 빈 문자열과 일치합니다. 그렇지 않으면 0개 또는 1개의 공백 문자와 통화 기호를 찾습니다.

설명

일치 항목 검색은 input 문자열의 시작 부분에서 시작됩니다. 정규식은 현재 Regex 개체에 대한 생성자가 정의한 패턴입니다.

replacement 매개 변수는 input각 일치 항목을 바꿀 문자열을 지정합니다. replacement 리터럴 텍스트와 대체조합으로 구성 될 수 있습니다. 예를 들어 a*${test}b 대체 패턴은 문자열 "a*"를 삽입한 다음 test 캡처링 그룹과 일치하는 부분 문자열(있는 경우) 뒤에 문자열 "b"를 삽입합니다. * 문자는 대체 패턴 내에서 메타 문자로 인식되지 않습니다.

메모

대체는 대체 패턴에서 인식되는 유일한 정규식 언어 요소입니다. 문자 이스케이프를 비롯한 다른 모든 정규식 언어 요소는 정규식 패턴에서만 허용되며 대체 패턴에서는 인식되지 않습니다.

대체 작업의 실행 시간이 Regex.Regex(String, RegexOptions, TimeSpan) 생성자가 지정한 제한 시간 간격을 초과하면 RegexMatchTimeoutException 예외가 throw됩니다. 생성자를 호출할 때 제한 시간 간격을 설정하지 않으면 작업이 Regex 개체가 만들어진 애플리케이션 도메인에 대해 설정된 제한 시간 값을 초과하면 예외가 throw됩니다. Regex 생성자 호출 또는 애플리케이션 도메인의 속성에 제한 시간이 정의되지 않거나 제한 시간 값이 Regex.InfiniteMatchTimeout경우 예외가 throw되지 않습니다.

일치하는 항목이 없으면 메서드가 변경되지 input 반환하므로 Object.ReferenceEquals 메서드를 사용하여 메서드가 입력 문자열을 대체했는지 여부를 확인할 수 있습니다.

추가 정보

적용 대상

Replace(String, String, Int32, Int32)

Source:
Regex.Replace.cs
Source:
Regex.Replace.cs
Source:
Regex.Replace.cs

지정된 입력 부분 문자열에서 정규식 패턴과 일치하는 지정된 최대 문자열 수를 지정된 대체 문자열로 대체합니다.

public:
 System::String ^ Replace(System::String ^ input, System::String ^ replacement, int count, int startat);
public string Replace (string input, string replacement, int count, int startat);
member this.Replace : string * string * int * int -> string
Public Function Replace (input As String, replacement As String, count As Integer, startat As Integer) As String

매개 변수

input
String

일치 항목을 검색할 문자열입니다.

replacement
String

대체 문자열입니다.

count
Int32

교체가 발생할 수 있는 최대 횟수입니다.

startat
Int32

검색이 시작되는 입력 문자열의 문자 위치입니다.

반환

대체 문자열이 일치하는 각 문자열을 대신한다는 점을 제외하고 입력 문자열과 동일한 새 문자열입니다. 정규식 패턴이 현재 인스턴스에서 일치하지 않으면 메서드는 변경되지 않은 현재 인스턴스를 반환합니다.

예외

input 또는 replacementnull.

startat 0보다 작거나 input길이보다 큽니다.

시간 초과가 발생했습니다. 제한 시간에 대한 자세한 내용은 주의 섹션을 참조하세요.

예제

다음은 문자열의 첫 번째 줄을 제외한 모든 줄을 이중 공백으로 지정하는 예제입니다. 텍스트 줄과 일치하고, 문자열의 첫 번째 줄과 일치하도록 Match(String) 메서드를 호출하고, Match.IndexMatch.Count 속성을 사용하여 두 번째 줄의 시작 위치를 결정하는 정규식 패턴 ^.*$정의합니다.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string input = "Instantiating a New Type\n" +
                     "Generally, there are two ways that an\n" + 
                     "instance of a class or structure can\n" +
                     "be instantiated. ";
      string pattern = "^.*$";
      string replacement = "\n$&";
      Regex rgx = new Regex(pattern, RegexOptions.Multiline);
      string result = String.Empty; 
      
      Match match = rgx.Match(input);
      // Double space all but the first line.
      if (match.Success) 
         result = rgx.Replace(input, replacement, -1, match.Index + match.Length + 1);

      Console.WriteLine(result);                     
   }
}
// The example displays the following output:
//       Instantiating a New Type
//       
//       Generally, there are two ways that an
//       
//       instance of a class or structure can
//       
//       be instntiated.
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim input As String = "Instantiating a New Type" + vbCrLf + _
                            "Generally, there are two ways that an" + vbCrLf + _
                            "instance of a class or structure can" + vbCrLf + _
                            "be instantiated. "
      Dim pattern As String = "^.*$"
      Dim replacement As String = vbCrLf + "$&"
      Dim rgx As New Regex(pattern, RegexOptions.Multiline)
      Dim result As String = String.Empty 
      
      Dim match As Match = rgx.Match(input)
      ' Double space all but the first line.
      If match.Success Then 
         result = rgx.Replace(input, replacement, -1, match.Index + match.Length + 1)
      End If
      Console.WriteLine(result)                      
   End Sub
End Module
' The example displays the following output:
'       Instantiating a New Type
'       
'       Generally, there are two ways that an
'       
'       instance of a class or structure can
'       
'       be instntiated.

^.*$ 정규식 패턴은 다음 표와 같이 정의됩니다.

무늬 묘사
^ 줄의 시작 부분과 일치합니다. (Regex 개체는 RegexOptions.Multiline 옵션을 사용하여 인스턴스화되었습니다. 그렇지 않으면 이 문자 클래스는 입력 문자열의 시작 부분만 일치합니다.)
.* 문자를 0번 이상 일치합니다.
$ 줄의 끝과 일치합니다. (Regex 개체는 RegexOptions.Multiline 옵션을 사용하여 인스턴스화되었습니다. 그렇지 않으면 이 문자 클래스는 입력 문자열의 시작 부분만 일치합니다.)

C#의 "\n$&" Visual Basic에서vbCrLf + "$&" 대체 문자열은 일치하는 문자열 앞에 새 줄을 추가합니다. C# 예제의 \n C# 컴파일러에 의해 줄 바꿈 문자로 해석됩니다. 정규식 문자 이스케이프를 나타내지 않습니다.

설명

일치 항목 검색은 startat 매개 변수로 지정된 위치에 있는 input 문자열에서 시작됩니다. 정규식은 현재 Regex 개체에 대한 생성자가 정의한 패턴입니다. count 음수이면 대체 항목이 문자열의 끝으로 계속 바꿉니다. count 일치 항목 수를 초과하면 모든 일치 항목이 바뀝니다.

startat대한 자세한 내용은 Match(String, Int32)주의 섹션을 참조하세요.

replacement 매개 변수는 input각 일치 항목을 바꿀 문자열을 지정합니다. replacement 리터럴 텍스트와 대체조합으로 구성 될 수 있습니다. 예를 들어 a*${test}b 대체 패턴은 문자열 "a*"를 삽입한 다음 test 캡처링 그룹과 일치하는 부분 문자열(있는 경우) 뒤에 문자열 "b"를 삽입합니다. * 문자는 대체 패턴 내에서 메타 문자로 인식되지 않습니다.

메모

대체는 대체 패턴에서 인식되는 유일한 정규식 언어 요소입니다. 문자 이스케이프를 비롯한 다른 모든 정규식 언어 요소는 정규식 패턴에서만 허용되며 대체 패턴에서는 인식되지 않습니다.

대체 작업의 실행 시간이 Regex.Regex(String, RegexOptions, TimeSpan) 생성자가 지정한 제한 시간 간격을 초과하면 RegexMatchTimeoutException 예외가 throw됩니다. 생성자를 호출할 때 제한 시간 간격을 설정하지 않으면 작업이 Regex 개체가 만들어진 애플리케이션 도메인에 대해 설정된 제한 시간 값을 초과하면 예외가 throw됩니다. Regex 생성자 호출 또는 애플리케이션 도메인의 속성에 제한 시간이 정의되지 않거나 제한 시간 값이 Regex.InfiniteMatchTimeout경우 예외가 throw되지 않습니다.

일치하는 항목이 없으면 메서드가 변경되지 input 반환하므로 Object.ReferenceEquals 메서드를 사용하여 메서드가 입력 문자열을 대체했는지 여부를 확인할 수 있습니다.

추가 정보

적용 대상