How to remove characters from a string, except those in a list

后端 未结 5 2071
感情败类
感情败类 2021-01-24 05:16

This is my string value:

string str = \"32 ab d32\";

And this list is my allowed characters:

var allowedCharacters = new List&l         


        
5条回答
  •  没有蜡笔的小新
    2021-01-24 05:49

    Try this:

    string srVariable = "32 ab d32";
    List lstAllowedCharacters = new List { "a", "b", "c", "2", " " };
    
    srVariable = Regex.Replace(srVariable, "[^" + Regex.Escape(string.Join("", lstAllowedCharacters) + "]"), delegate(Match m)
    {
        if (!m.Success) { return m.Value; }
        return " ";
    });
    
    Console.WriteLine(srVariable);
    

提交回复
热议问题