tags:

views:

85

answers:

5

What is the difference between below two regular expressions

(.|[\r\n]){1,1500}

^.{1,1500}$
+1  A: 

. does not match new lines.

KennyTM
It does if you specify `RegexOptions.SingleLine`.
cHao
+4  A: 

The first matches up-to-1500 chars, and the second (assuming you haven't set certain regex options) matches a first single line of up-to-1500 chars, with no newlines.

cHao
...and it (the second one) does so only if either the string contains no newlines at all, or the option `RegexOptions.Multiline` is set because otherwise the `$` means "end of string" instead of "end of line".
Tim Pietzcker
Ooo. Thanks for catching that.
cHao
:) a single line without newlines. Sounds cool.
serhio
+2  A: 

First expression matches some <= 1500 characters of the file(or other source).
Second expression matches a entire line with charsNumber <= 1500.

. matches any character except \n newline.

serhio
`.` can match all chars if you specify `RegexOptions.SingleLine`. But even then, there's a subtle difference; the first matches up-to-1500 chars, and the second matches *the first* up-to-1500 chars.
cHao
I am using this against multi line textbox of ASP.NET.While viewing this in safari i am getting error "Invalid regular expression: regular expression too large"
Nimesh
with both or only one of them?
serhio
first one is giving me error in safari 3.0. What i need to do is that, i need to restrict the user to enter more than 1500 characters and need to display an error message. i am using regular expression validator for this.
Nimesh
do you need 1500 chars per line, or in general?
serhio
in my text box i should be able to enter not more than 1500 characters. not in a line.
Nimesh
So you can use `(.|[\n]){1,1500}` (or use `regexOptions.Multiline`). Did you tried in other that Safari browsers?
serhio
yeah.. i tested this on safari 4.0, its working fine..
Nimesh
Safari... far to be a popular browser 3% of the market...
serhio
+1  A: 

The second one matches the first 1500 characteres of a line IF the line contains 1500 characters or less

rossoft
say not the *first*, but *all* of them.
serhio
@serhio: exactly
rossoft
+1  A: 

If it's for use in a RegularExpressionValidator, you probably want to use this regex:

^[\s\S]{1,1500}$

This is because the regex may be run on either the server (.NET) or the client (JavaScript). In .NET regexes you can use the RegexOptions.Singleline flag (or its inline equivalent, (?s)) to make the dot match newlines, but JavaScript has no such mechanism.

[\s\S] matches any whitespace character or anything that's not a whitespace character--in other words, anything. It's the most popular idiom for matching anything including a newline in JavaScript; it's much, much more efficient than alternation-based approaches like (.|\n).

Note that you'll still need to use a RequiredFieldValidator if you don't want the user to leave the textbox empty.

Alan Moore