18

I am trying to implement a regular expression that will check a string is between 1 - 50 characters. They are allowed to enter any characters.

I am new to creating regex expressions, but this is my attempt: ^{1,50}$

The reason I tried that is that I found this was the way to limit the characters.

7
  • What character are you allowing ?
    – user2705585
    Mar 24, 2016 at 9:28
  • 3
    . will match any one character, so ^.{1,50}$ Mar 24, 2016 at 9:29
  • 4
    ^.{1,50}$ - you missed the dot. But I'm pretty sure that C# has methods to check string length without using regex. Mar 24, 2016 at 9:30
  • 2
    Why not just put MyString.Length <= 50? Mar 24, 2016 at 9:31
  • 1
    We use a validation engine which is done with regex to keep all validation in one place.
    – Ben Clarke
    Mar 24, 2016 at 9:32

5 Answers 5

35

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

17

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)
2

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.

1
  • 1
    If you have 60 characters it will match first 50 and leave remaining 10. The entire string has to be within range. Adding anchors will solve this problem like this ^.{1,50}$
    – user2705585
    Mar 24, 2016 at 9:42
2

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
}
1
  • 1
    @noob yes, this will work on multiline strings as well (but each newline char will count towards the length) Mar 24, 2016 at 9:37
1

To allow all characters, you use . in regex.

So, to have a maximum 50 character string, you'd do:

^.{1,50}$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.