Nic*_*ick 5 c# regex whitespace
我有以下代码:
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);
}
Run Code Online (Sandbox Code Playgroud)
这允许在文本框中使用空格,如何也防止插入空格?
在正则表达式中,\s修饰符转换为[\r\n\t\f ],这意味着没有newline字符,没有tab字符,没有form feed字符(打印机使用它来开始新页面),并且没有spaces。
所以你可以使用正则表达式[^\\s](你必须使用\\才能创建一个单一的\,然后它将转换为\sfinally。如果你只是使用\s,它将转换为 s 字符文字。
开头和结尾^以及$字符分别匹配字符串的开头和结尾。
所以,你可以使用正则表达式^[^0-9\\s]+$。以下是它的作用的详细说明:
^匹配字符串的开头。[],它将匹配该组中的任何单个字符[],我们有^0-9\\s:
^字符确保 中的任何单个字符都[]不会被匹配(将其从任何单个字符切换为无单个字符),以下情况都不应该为真0-9部分匹配 0 到 9 之间的任意数字\\s部分从字面上创造\s。\s匹配任何空白字符+的组的匹配[]$匹配字符串的结尾您的代码可能是:
private static bool IsTextAllowed(string text){
Regex regex = new Regex("^[^0-9\\s]+$");
return !regex.IsMatch(text);
}
Run Code Online (Sandbox Code Playgroud)
这是 regex101 测试:https ://regex101.com/r/aS9xT0
| 归档时间: |
|
| 查看次数: |
7646 次 |
| 最近记录: |