c# - WPF 中的 KeyDown 事件中使用正则表达式不限制某些特殊字符

标签 c# regex

我试图限制除英文字母以外的所有字符,但我仍然可以输入一些顽皮的字符,这不太好!我怎样才能防止这种情况发生。这些顽皮的字符没有被我的正则表达式捕获是 - _ + = ? < > '

private void AlphaOnlyTextBox_OnKeyDown(object sender, KeyEventArgs e)
{    
    var restrictedChars = new Regex(@"[^a-zA-Z\s]");

    var match = restrictedChars.Match(e.Key.ToString());

    // Check for a naughty character in the KeyDown event.
    if (match.Success)
    {
        // Stop the character from being entered into the control since it is illegal.
        e.Handled = true;
    }
}

<Window x:Class="WpfApplication4.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>

        <TextBox Height="21"
                 Width="77" 
                 MaxLength="2"
                 KeyDown="AlphaOnlyTextBox_OnKeyDown"
                                           >
        </TextBox>
    </Grid>
</Window>

最佳答案

尝试这个表达式:

var restrictedChars = new Regex(@"[^(\W_0-9)]+");

它将排除除大写字母和小写字母字符之外的所有内容(不取决于特定语言)。

希望对你有帮助!

关于c# - WPF 中的 KeyDown 事件中使用正则表达式不限制某些特殊字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38313281/

相关文章:

python - 如何使用正则表达式从字符串中提取数字并返回最后 3 个或更少的数字

.net - 将 PHP 正则表达式转换为 .NET

java - regex\\p{So} 不过滤 BLACK CIRCLE FOR RECORD

c# - 结构体 "this"的含义 (C#)

C# 身份 : howto find and update different identity's claims in UserStore?

regex - Htaccess 公用文件夹重写规则

regex - 如何配置 nginx.ingress.kubernetes.io/rewrite-target 和 spec.rules.http.paths.path 以满足以下 URI 模式

c# - WPF 使用 Magstrip 编码打印到打印机

c# - 如何向 R# 指示函数检查变量是否为 null

c# - Azure Devops 中针对不同环境的 app.config 转换