Removing word or character from string followed by space or before space in c#

前端 未结 6 1176
悲哀的现实
悲哀的现实 2021-01-25 00:55

I have a string

string name = \"AL QADEER UR AL REHMAN AL KHALIL UN\";

How would I remove all characters AL, UR,

6条回答
  •  深忆病人
    2021-01-25 01:14

    static void TestRegex()
    {
        string name = "AL QADEER UR AL REHMAN AL KHALIL UN";
        // Add other strings you want to remove
        string pattern = @"\b(AL|UR|UN)\b";
        name = Regex.Replace(name, pattern, String.Empty);
        // Remove extra spaces
        name = Regex.Replace(name, @"\s{2,}", " ").Trim();
        Console.WriteLine(name);
    }
    

    UPDATE

    You can generate the pattern this way:

    // Generate pattern
    var list = new List { "AL", "UR", "UN" };
    string pattern = @"\b(" + String.Join("|", list) + @")\b";
    

提交回复
热议问题