Disallow whitespaces in regex

≡放荡痞女 提交于 2020-05-23 13:06:08

问题


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-9 part matches any number between 0 and 9
    • The \\s part creates literally \s. \s matches any whitespace character
  • 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!