gpt4 book ai didi

c# - 在 WPF 的 KeyDown 事件中使用 Regex 不限制某些特殊字符

转载 作者:行者123 更新时间:2023-11-30 20:35:13 25 4
gpt4 key购买 nike

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

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 事件中使用 Regex 不限制某些特殊字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38313281/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com