排除某些字符无法将它们写入文本框

exclude some characters from being able to write them in textbox

晚上好,

尝试排除某些字符,使其无法写入文本框, 我写了这段代码,它有效

private void N_Text_TextChanged(object sender, TextChangedEventArgs e)
    {
        if (N_Text.Text.Contains("<") || N_Text.Text.Contains(">") || N_Text.Text.Contains(@"\")
            || N_Text.Text.Contains("/") || N_Text.Text.Contains(";") || N_Text.Text.Contains(":")
            || N_Text.Text.Contains(",") || N_Text.Text.Contains("*") || N_Text.Text.Contains("?")
            || N_Text.Text.Contains("=") || N_Text.Text.Contains("|") || N_Text.Text.Contains("`")
            || N_Text.Text.Contains("\""))
        {
            N_Text.Clear();
        }
    }

但是有没有更好的方法(捷径),例如正则表达式?

如何只删除文本框中的字符,因为 .Clear(); 清除所有文本 ??

谢谢。

同样的问题here。 可以使用 Regex.Replace.

取自链接问题的代码示例。我添加测试输入字符串并使用您示例中的符号作为正则表达式模式:

string input = "\"\"   Here<<  is my  >> very \ lovely // string, where ::: I** wish? to === replace || unliked `` chars \"\" ";       
string pattern = "[<>\/;:,*?=|`\"]"; // Your unliked chars and symbols
string replacement = string.Empty; // Simply replace to nothing
        
string result = Regex.Replace(input, pattern, replacement);
// Here would be "   Here  is my   very  lovely  string where  I wish to  replace  unliked  chars"

此外,还提供了第二个 Regex 替换以删除一行中的多个空格。我只添加 Trim 来清除输入字符串开头和结尾的空格:

result = Regex.Replace(result, @"\s+", " ").Trim(' ')
// Here would be "Here is my very lovely string where I wish to replace unliked chars"

因此,对您的示例进行两个替换的最终改编可能是这样的:

private void N_Text_TextChanged(object sender, TextChangedEventArgs e)
{
   N_Text.Text = Regex.Replace(Regex.Replace(N_Text.Text, "[<>\/;:,*?=|`\"]", string.Empty), @"\s+", " ").Trim(' ');    
}

您还可以创建一个扩展方法:

public static class Extensions
{
    public static string ReplaceSymbols(this string input)
    {
        return Regex.Replace(Regex.Replace(input, "[<>\/;:,*?=|`\"]", string.Empty), @"\s+", " ").Trim(' ');
    }
        
    // Or in lambda style       
    // public static string ReplaceSymbols(this string input) => Regex.Replace(Regex.Replace(input, "[<>\/;:,*?=|`\"]", string.Empty), @"\s+", " ").Trim(' ');
}

简单地称之为:

private void N_Text_TextChanged(object sender, TextChangedEventArgs e)
{
   N_Text.Text = N_Text.Text.ReplaceSymbols();    
}

确保您不要忘记添加对 System.Text.RegularExpressions 的引用并注意连续的双反斜杠。