Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disallow whitespaces in regex

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?

like image 654
Nick Avatar asked Jan 01 '15 19:01

Nick


1 Answers

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

like image 88
Jojodmo Avatar answered Sep 28 '22 18:09

Jojodmo