Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression to limit string length

Tags:

regex

asp.net

I have an issue where I need to use a RegularExpressionValidator to limit the length of a string to 400 Characters.

My expression was .{0,400}

My question: Is there a way to limit the length of characters to 400 without taking into consideration blank spaces?

I want to be able to accept blank spaces in the string but not count it in the length. Is this possible?

like image 611
Boopid Avatar asked Jun 09 '09 21:06

Boopid


2 Answers

I pretty much agree with Greg, but here's the regex you want:

^\s*([^\s]\s*){0,400}$

@Boopid: If you really meant only the space character, replace \s with a space in the regex.

like image 88
RichieHindle Avatar answered Sep 27 '22 19:09

RichieHindle


It sounds like you might want to write your own validator class instead of using the RegularExpressionValidator. Regular expressions certainly have their uses, but this doesn't sound like one of them.

Your custom validator could remove all the spaces, then check the length of the string. Ultimately, the code will be more readable than a regular expression that does the same thing.

like image 39
Greg Hewgill Avatar answered Sep 27 '22 18:09

Greg Hewgill