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) 다음 조건 중 하나라도 true인 경우 정규식 일치를 바꾸는 데 유용합니다.

  • 대체 문자열은 정규식 대체 패턴으로 쉽게 지정할 수 없습니다.
  • 대체 문자열은 일치하는 문자열에서 수행된 일부 처리의 결과입니다.
  • 대체 문자열은 조건부 처리의 결과입니다.

메서드는 메서드를 호출 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

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

RegexMatchTimeoutException 대체 작업의 실행 시간이 생성자가 지정한 제한 시간 간격을 초과하는 경우 예외가 Regex.Regex(String, RegexOptions, TimeSpan) throw됩니다. 생성자를 호출할 때 시간 제한 간격을 설정 하지 않으면, 작업이 있는 애플리케이션 도메인에 설정 된 제한 시간 값을 초과 하면 예외가 throw 되는 Regex 개체가 만들어집니다. 제한 시간에 정의 된 경우는 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 생성하고 instance 메서드 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입니다.

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

또는

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) 다음 조건 중 하나라도 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 하면 일치 항목 검색이 입력 문자열의 끝에서 시작되고 왼쪽으로 이동합니다. 그렇지 않으면 입력 문자열의 시작 부분에 검색이 시작되고 오른쪽으로 이동합니다.

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

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

호출자 참고

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

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

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

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

추가 정보

적용 대상

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입니다.

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

시간이 초과되었습니다. 시간 제한에 대한 자세한 내용은 설명 섹션을 참조하세요.

예제

다음 예제에서는 정규식을 사용하여 문자열에서 개별 단어를 추출한 다음 대리자를 사용하여 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입니다.

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

또는

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 생성하고 instance 메서드 Replace를 호출하는 것과 같습니다.

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

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

참고

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

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

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

호출자 참고

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

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

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

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

추가 정보

적용 대상

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입니다.

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

시간이 초과되었습니다. 시간 제한에 대한 자세한 내용은 설명 섹션을 참조하세요.

예제

다음 예제에서는 메서드를 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 생성하고 instance 메서드 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) 다음 조건 중 하나라도 true인 경우 정규식 일치를 바꾸는 데 유용합니다.

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

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

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

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

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

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

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

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

RegexMatchTimeoutException 대체 작업의 실행 시간이 생성자가 지정한 제한 시간 간격을 초과하면 예외가 Regex.Regex(String, RegexOptions, TimeSpan) throw됩니다. 생성자를 호출할 때 시간 제한 간격을 설정 하지 않으면, 작업이 있는 애플리케이션 도메인에 설정 된 제한 시간 값을 초과 하면 예외가 throw 되는 Regex 개체가 만들어집니다. 제한 시간에 정의 된 경우는 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$1을 사용하여 메서드를 Replace(String, String, String) 호출하여 반전됩니다.

설명

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

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

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

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

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

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

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

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

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

RegexMatchTimeoutException 대체 작업의 실행 시간이 생성자가 지정한 제한 시간 간격을 초과하면 예외가 Regex.Regex(String, RegexOptions, TimeSpan) throw됩니다. 생성자를 호출할 때 시간 제한 간격을 설정 하지 않으면, 작업이 있는 애플리케이션 도메인에 설정 된 제한 시간 값을 초과 하면 예외가 throw 되는 Regex 개체가 만들어집니다. 제한 시간에 정의 된 경우는 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) 다음 조건 중 하나라도 true인 경우 정규식 일치를 바꾸는 데 유용합니다.

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

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

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

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

참고

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

RegexMatchTimeoutException 대체 작업의 실행 시간이 생성자가 지정한 제한 시간 간격을 초과하면 예외가 Regex.Regex(String, RegexOptions, TimeSpan) throw됩니다. 생성자를 호출할 때 시간 제한 간격을 설정 하지 않으면, 작업이 있는 애플리케이션 도메인에 설정 된 제한 시간 값을 초과 하면 예외가 throw 되는 Regex 개체가 만들어집니다. 제한 시간에 정의 된 경우는 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번 이상 나오는 공백 문자를 찾습니다.
(\p{Sc}\s?)? 0개 또는 1개의 통화 기호 조합과 0개 또는 1개의 공백 문자를 찾습니다. 이 그룹은 첫 번째 캡처링 그룹입니다.
\d+ 하나 이상의 10진수 숫자가 일치하는지 확인합니다.
\.? 마침표가 0개 또는 1개(소수 구분 기호 문자로 사용됨)와 일치합니다.
((?<=\.)\d+)? 마침표가 이전 문자인 경우 하나 이상의 10진수를 찾습니다. 이 패턴은 0번 또는 한 번 일치시킬 수 있습니다.
(\d+\.?((?<=\.)\d+)?) 하나 이상의 10진수 패턴과 선택적 마침표 및 추가 10진수를 찾습니다. 이 그룹은 두 번째 캡처링 그룹입니다. 메서드를 Replace(String, String) 호출하면 전체 일치 항목이 캡처된 그룹의 값으로 바뀝니다.
(?(1)|\s?\p{Sc})? 캡처된 첫 번째 그룹이 있는 경우 빈 문자열과 일치합니다. 그렇지 않으면 0개 또는 1개의 공백 문자와 통화 기호를 찾습니다.

설명

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

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

참고

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

RegexMatchTimeoutException 대체 작업의 실행 시간이 생성자가 지정한 제한 시간 간격을 초과하면 예외가 Regex.Regex(String, RegexOptions, TimeSpan) throw됩니다. 생성자를 호출할 때 시간 제한 간격을 설정 하지 않으면, 작업이 있는 애플리케이션 도메인에 설정 된 제한 시간 값을 초과 하면 예외가 throw 되는 Regex 개체가 만들어집니다. 제한 시간에 정의 된 경우는 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.Count 속성을 사용하여 Match.Index 두 번째 줄의 시작 위치를 결정하는 정규식 패턴 를 정의합니다.

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 개체를 인스턴스화했습니다. 그렇지 않으면 이 문자 클래스는 입력 문자열의 시작 부분만 일치합니다.)

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

설명

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

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

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

참고

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

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

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

추가 정보

적용 대상