【问题标题】:C# Regex Replace Greek LettersC# 正则表达式替换希腊字母
【发布时间】:2022-01-10 07:44:48
【问题描述】:

我得到像“thetaetaA”这样的字符串(theta eta A) 我需要替换收到的字符串,例如 {\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);

有人可以告诉我如何创建所需的文本 {\theta}{\eta}A

如果我使用循环并替换它会生成以下输出

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

因为 theta 包含 eta

【问题讨论】:

    标签: c# regex


    【解决方案1】:

    Regex.Matches() 不会取代任何东西。使用Regex.Replace()。捕获单词并在替换中引用捕获,并在其周围添加特殊字符。 (并且可能在交替中的子字符串之前有超字符串。虽然它对我来说两种方式都有效。据说无论如何它都是一个贪婪的匹配。)

    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();
        }
    }
    

    【讨论】:

    • 这非常有效。非常感谢
    猜你喜欢
    • 2011-01-30
    • 2018-04-09
    • 2011-08-20
    • 1970-01-01
    • 2016-12-28
    • 2020-10-16
    • 2018-05-28
    • 2013-11-26
    • 2021-10-07
    相关资源
    最近更新 更多