如何从字符串中删除字符,列表中的字符除外

时间:2012-12-11 16:45:05

标签: c# regex list replace character

这是我的字符串值:

string str = "32 ab d32";

此列表是我允许的字符:

var allowedCharacters = new List<string> { "a", "b", "c", "2", " " };

我希望它成为:

str == " 2 ab   2";

我想用空格替换任何不在允许字符列表中的字符。

5 个答案:

答案 0 :(得分:5)

没有正则表达式:

IEnumerable<Char> allowed = srVariable
    .Select(c => lstAllowedCharacters.Contains(c.ToString()) ? c : ' ');
string result = new string(allowed.ToArray());

答案 1 :(得分:2)

试试这个:

string srVariable = "32 ab d32";
List<string> lstAllowedCharacters = new List<string> { "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);

答案 2 :(得分:2)

正则表达式?对于你想要完成的事情,正则表达式可能有点过分。

这是另一种没有正则表达式的变体(将lstAllowedCharacters修改为实际上是字符的可枚举,而不是字符串[如变量名称所暗示的那样]):

String original = "32 ab d32";
Char replacementChar = ' ';
IEnumerable<Char> allowedChars = new[]{ 'a', 'b', 'c', '2', ' ' };

String result = new String(
  original.Select(x => !allowedChars.Contains(x) ? replacementChar : x).ToArray()
);

答案 3 :(得分:1)

这是一个简单但高效的foreach解决方案:

Hashset<char> lstAllowedCharacters = new Hashset<char>{'a','b','c','2',' '};

var resultStrBuilder = new StringBuilder(srVariable.Length);

foreach (char c in srVariable) 
{
    if (lstAllowedCharacters.Contains(c))
    {
        resultStrBuilder.Append(c);
    }
    else
    {
        resultStrBuilder.Append(" ");
    }
}

srVariable = resultStrBuilder.ToString();

答案 4 :(得分:0)

为什么不使用String.Replace