我有这个代码:
private static bool IsTextAllowed(string text)
{
Regex regex = new Regex("[^0-9]+"); // Regex that matches disallowed text
return !regex.IsMatch(text);
}
private void TextboxClientID_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
e.Handled = !IsTextAllowed(e.Text);
}
这允许在文本框中插入空格,如何防止插入空格?
最佳答案
在正则表达式中,\s
修饰符转换为 [\r\n\t\f ]
,这意味着没有 newline
字符,没有 tab
字符,没有 form feed
字符(打印机用来开始一个新页面),也没有 spaces
。
因此您可以使用正则表达式 [^\\s]
(您必须使用 \\
才能生成单个 \
, 最后会翻译成\s
。如果你只使用\s
,它会翻译成s字面量。
开头和结尾的^
和$
字符分别匹配字符串的开头和结尾。
因此,您可以使用正则表达式 ^[^0-9\\s]+$
。以下是其功能的分割:
- 第一个
^
匹配字符串的开头。 - 接下来,我们将组包含在
[]
中,它将匹配该组中的任何单个字符 - 在
[]
中,我们有^0-9\\s
:^
字符确保不会匹配[]
中的任何单个字符(将其从任何单个字符切换为没有单个字符),以下应该是正确的0-9
部分匹配 0 到 9 之间的任意数字\\s
部分按字面意思创建\s
。\s
匹配任何空白字符
+
匹配包含在[]
中的组 1 到无限次- 最后的
$
匹配字符串的结尾
您的代码可以是:
private static bool IsTextAllowed(string text){
Regex regex = new Regex("^[^0-9\\s]+$");
return !regex.IsMatch(text);
}
这是一个 regex101 测试:https://regex101.com/r/aS9xT0
关于c# - 不允许在正则表达式中使用空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27733961/