MatchEvaluator Delegato

Definizione

Rappresenta il metodo chiamato ogni volta che si individua una corrispondenza di un'espressione regolare durante un'operazione del metodo Replace.

C#
public delegate string MatchEvaluator(Match match);
C#
[System.Serializable]
public delegate string MatchEvaluator(Match match);

Parametri

match
Match

Oggetto Match che rappresenta una corrispondenza di un'espressione regolare singola durante un'operazione del metodo Replace.

Valore restituito

Stringa restituita dal metodo rappresentato dal delegato MatchEvaluator.

Attributi

Esempio

Nell'esempio di codice seguente viene usato il MatchEvaluator delegato per sostituire ogni gruppo di caratteri corrispondente con il numero di occorrenze della corrispondenza.

C#
using System;
using System.Text.RegularExpressions;

class MyClass
{
   static void Main(string[] args)
   {
      string sInput, sRegex;

      // The string to search.
      sInput = "aabbccddeeffcccgghhcccciijjcccckkcc";

      // A very simple regular expression.
      sRegex = "cc";

      Regex r = new Regex(sRegex);
        
      MyClass c = new MyClass();

      // Assign the replace method to the MatchEvaluator delegate.
      MatchEvaluator myEvaluator = new MatchEvaluator(c.ReplaceCC);
        
      // Write out the original string.
      Console.WriteLine(sInput);

      // Replace matched characters using the delegate method.
      sInput = r.Replace(sInput, myEvaluator);
      
      // Write out the modified string.
      Console.WriteLine(sInput);
   }

   public string ReplaceCC(Match m)
   // Replace each Regex cc match with the number of the occurrence.
   {
      i++;
      return i.ToString() + i.ToString();		
   }
   public static int i=0;
}
// The example displays the following output:
//       aabbccddeeffcccgghhcccciijjcccckkcc
//       aabb11ddeeff22cgghh3344iijj5566kk77

Commenti

È possibile usare un MatchEvaluator metodo delegato per eseguire un'operazione di verifica o manipolazione personalizzata per ogni corrispondenza trovata da un metodo sostitutivo, Regex.Replace(String, MatchEvaluator)ad esempio . Per ogni stringa corrispondente, il metodo chiama il ReplaceMatchEvaluator metodo delegato con un Match oggetto che rappresenta la corrispondenza. Il metodo delegato esegue qualsiasi elaborazione preferita e restituisce una stringa che il Replace metodo sostituisce per la stringa corrispondente.

Metodi di estensione

GetMethodInfo(Delegate)

Ottiene un oggetto che rappresenta il metodo rappresentato dal delegato specificato.

Si applica a

Prodotto Versioni
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

Vedi anche