这是我的字符串值:
string str = "32 ab d32";
这个列表是我允许的字符:
var allowedCharacters = new List<string> { "a", "b", "c", "2", " " };
我希望它变成:
str == " 2 ab 2";
我想用空格替换不在允许字符列表中的任何字符。
没有正则表达式:
IEnumerable<Char> allowed = srVariable
.Select(c => lstAllowedCharacters.Contains(c.ToString()) ? c : ' ');
string result = new string(allowed.ToArray());
尝试这个:
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);
正则表达式?正则表达式对于您要完成的工作可能有点矫枉过正。
这是没有正则表达式的另一种变体(将您修改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()
);
你为什么不使用String.Replace?
这是一个简单但高效的 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();