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

前端 未结 6 1175
悲哀的现实
悲哀的现实 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<string> { "AL", "UR", "UN" };
    string pattern = @"\b(" + String.Join("|", list) + @")\b";
    
    0 讨论(0)
  • 2021-01-25 01:20

    Try this please :

    var name = "AL QADEER UR AL REHMAN AL KHALIL UN";
    var list = new List<string> { "AL", "UR", "UN" };
    name = string.Join(" ", name.Split(' ').ToList().Except(list));
    
    0 讨论(0)
  • 2021-01-25 01:23

    Pure LINQ answer with the help of EXCEPT

    string name = "AL QADEER UR AL REHMAN AL KHALIL UN";
    var list = new string[] { "AL", "UR", "UN" };
    
    name = name
       .Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries)
       .Except(list)
       .Aggregate((prev, next) => $"{prev} {next}");
    

    OUTPUT: QADEER REHMAN KHALIL

    0 讨论(0)
  • 2021-01-25 01:24

    I am loading that list from database, and can be change any time, how do use this in regex when changes occur

    okay then, the length would always be 2?

    no, but not be greater than 4

    public static void Main()
    {
        var input = "AL QADEER UR AL REHMAN AL KHALIL UN AAA BBB";
        Regex re = new Regex(@"\b\w{1,4}\b");
        var result = re.Replace(input, "");
        Console.WriteLine(result);
    }
    

    OUTPUT:

    QADEER REHMAN KHALIL
    

    dotNetFiddle

    0 讨论(0)
  • 2021-01-25 01:26
    var words = new[] { "AL", "UR", "UN" };
    var arr = systemName.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries).Except(words);
    systemName = string.Join(" ", arr);
    
    0 讨论(0)
  • 2021-01-25 01:32

    No need to use regular expressions. Having defined list with "prohibited" words, it's enough to iterate over wprds in the sentence to filter, if word is in the list of prohibited words, then exclude it, otherwise, include the word in final string.

    Try this:

    string name = "AL QADEER UR AL REHMAN AL KHALIL UN";
    string systemName = "";
    List<string> list = new List<string> { "AL", "UR", "UN" };
    
    foreach (var item in name.Split(new char[] { ' ', ',', '.' }, StringSplitOptions.RemoveEmptyEntries))
        systemName += list.Contains(item) ? "" : item + " ";
    
    0 讨论(0)
提交回复
热议问题