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

后端 未结 5 1987
感情败类
感情败类 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:52

    Regex? Regex may be overkill for what you're trying to accomplish.

    Here's another variation without regex (modified your lstAllowedCharacters to actually be an enumerable of characters and not strings [as the variable name implies]):

    String original = "32 ab d32";
    Char replacementChar = ' ';
    IEnumerable allowedChars = new[]{ 'a', 'b', 'c', '2', ' ' };
    
    String result = new String(
      original.Select(x => !allowedChars.Contains(x) ? replacementChar : x).ToArray()
    );
    

提交回复
热议问题