Home > Net >  C# Regex Replace Greek Letters
C# Regex Replace Greek Letters

Time:12-04

I'm getting string like "thetaetaA" (theta eta A) I need to replace the recived string like {\theta}{\eta}A

// C# code with regex to match greek letters
string gl = "alpha|beta|delata|theta|eta";
string recived = "thetaetaA";
var greekLetters = Regex.Matches(recived,gl);

could someone please tell how can I create the required text {\theta}{\eta}A

if I use loop and do a replace it generate following out put

{\th{\eta}}{\eta}A

because theta included eta

CodePudding user response:

Regex.Matches() doesn't replace anything. Use Regex.Replace(). Capture the words and reference the capture in the replacement adding the special characters around it. (And possibly have the superstrings before the substrings in the alternation. Though it works either way for me. Supposedly it's a greedy match anyway.)

class Program
{
    static void Main(string[] args)
    {
        string gl = "alpha|beta|delta|theta|eta";
        string received = "thetaetaA";
        string texified = Regex.Replace(received, $"({gl})", @"{\$1}");

        Console.WriteLine(texified);

        Console.ReadKey();
    }
}

CodePudding user response:

Add your code RegexOptions.IgnoreCase

var greekLetters = Regex.Matches(recived, gl, RegexOptions.IgnoreCase);
  • Related