简体   繁体   English

Unicode正则表达式

[英]Unicode Regular Expressions

I'm trying to handle the keys that are pressed from keyboard. 我正在尝试处理从键盘按下的键。 So I made this Regex according to Regex Unicode : 所以我根据Regex Unicode制作了这个Regex:

private void tbName_KeyDown(object sender, KeyRoutedEventArgs e)
{
    if (!Regex.IsMatch(e.Key.ToString(), @"^[\p{L}\p{Z}]$"))
    {
       e.Handled = true;
    }
}

The problem is that it's only accepting letters, but white spaces (\\p{Z}) not, and it should accept. 问题在于它仅接受字母,但不接受空格(\\ p {Z}),因此应该接受。

Btw, I tried \\s (as usual), tried to put an "or" ( | ) between the 2 unicodes, but no way. 顺便说一句,我像往常一样尝试了\\ s,试图在两个unicode之间放置一个“或”(|),但是没有办法。 It definitively don't want to work. 它绝对不想工作。

EDIT 1: 编辑1:

I tested char.IsLetter, but it allows a lot of non-letters like: [ []^~´`ªº ] and all numbers of lateral numeric keyboard of notebook, for example, while Unicode Regex do not. 我测试了char.IsLetter,但是它允许很多非字母,例如:[[] ^〜´`ªº]和笔记本的所有横向数字键盘,而Unicode Regex则不允许。 So I want a solution with Regex. 所以我想用正则表达式解决方案。

The problem is not with your regex, but with e.Key.ToString() . 问题不在于您的正则表达式,而是e.Key.ToString() KeyRoutedEventArgs.Key is a value of the VirtualKey enum-type , such as Space or f5 or H . KeyRoutedEventArgs.KeyVirtualKey枚举类型的值,例如Spacef5H So your approach happens to work for letters — the name of the H key is H — but this is mostly a coincidence. 因此,您的方法碰巧适用于字母-H键的名称为H但这主要是巧合。

Using e.Key is fine, but you should examine the value either by comparing it to the enum constants, or by casting it to an int and looking at the numeric values (documented in the table above), or a mixture of these. 使用e.Key很好,但是您应该通过将其与枚举常量进行比较,或者将其强制转换为int并查看数字值(在上表中记录)或两者的混合来检查该值。

For example: 例如:

private void tbName_KeyDown(object sender, KeyRoutedEventArgs e)
{
    if (e.Key == VirtualKey.Space) {
        // ignore spaces
    } else if ((int)e.Key >= (int)VirtualKey.A && (int)e.Key <= (int)VirtualKey.Z) {
        // ignore letters
    } else {
        e.Handled = true;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM