问题
I have this code:
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);
}
This allows whitespaces in the textbox, how to prevent from inserting whitespaces too?
回答1:
In regex, the \s modifier translates to [\r\n\t\f ], which means no newline characters, no tab characters, no form feed characters (used by printers to start a new page), and no spaces.
So you can use the regex [^\\s] (you have to use \\ in order to make a single \, which will then translate to \s finally. If you just use \s, it will translate to s character literal.
The beginning and ending ^ and $ characters match the beginning and end of the string respectively.
So, you could use the regex ^[^0-9\\s]+$. Here is a breakdown of what it does:
- The first
^matches the beginning of the string. - Next, we have the group inclosed in
[], which will match any single character in that group - Inside of the
[], we have^0-9\\s:- The
^character makes sure that no single character inside of the[]will be matched (switches it from any single character to no single character), none of the following should be true - The
0-9part matches any number between 0 and 9 - The
\\spart creates literally\s.\smatches any whitespace character
- The
- The
+matches the group inclosed in[]between 1 and infinite times - The final
$matches the end of the string
Your code could be:
private static bool IsTextAllowed(string text){
Regex regex = new Regex("^[^0-9\\s]+$");
return !regex.IsMatch(text);
}
Here's a regex101 test: https://regex101.com/r/aS9xT0
回答2:
^[^0-9 ]+$
Try this.This will not allow whitespaces at all.
回答3:
Use:
@"^[^\d\s]+$"
\d ... Match a digit (0-9).
\s ... Match a whitespace character.
private static bool IsTextAllowed(string text)
{
return Regex.IsMatch(text, @"^[^\d\s]+$");
}
回答4:
*NOT a regex answer, I had the same issue with the space char's
I fixed this by adding PreviewKeyDown on the TextBox and setting e.Handled to true if spacebar has been pressed, just like this:
private void TextBox_PreviewKeyDown(object sender, KeyEventArgs e)
{
e.Handled = e.Key == Key.Space;
}
回答5:
Why do you bother with regex ? Simply use:
private static bool IsTextAllowed(string text)
{
return text.All(c => !char.IsWhiteSpace(c));
}
来源:https://stackoverflow.com/questions/27733961/disallow-whitespaces-in-regex