RegEx to allow all characters, length should be 1-50 characters

Just inspect the Length of the string:

string str = "less than 50 characters";
if(str.Length > 0 && str.Length <= 50)
{
    // Yay, we've got a winner
}

I suggest

.{1,50}

To generate regex expressions you can use Expresso, which is a free .NET regular expression development tool. Using this program, you will be able to build complex regular expressions just by selecting its different components from a menu. You can test the created expressions entering values to them.


Try ^.{1,50}$

Explanation:

  • . dot stands for all characters. Except \n for which you will have to use s DOTALL flag.

Regex101 Demo

Regular Expression Options


For the exact length of the string, you could use

^.{50}$

Whereas to check the length range you can use

^.{5,50}$

It might be more sensible for real users if I also included a lower limit on the number of letters.

If you wanted to just check the minimum length you can use

^.{50,}$

Now a string of at least fifty letters, but extending to any length,

^.{0,50}$

This will match a whole string containing between 0 and 50 (inclusive) of any character. Though regular expressions are probably the wrong tool for this job. Regex is overkill; just check the length of the string. You should have used String.Length for this, like:

if(UrString.Length > 0 && UrString.Length <= 50)

Tags:

C#

Regex