Groups | Blog | Home
all groups > c# > november 2007 >

c# : RegEx Help


slg
11/5/2007 10:59:55 PM
Gurus,
I am new to RegEx. How can i validate following.
All characters in my strings are [A-Za-z0-9] and underscore

The string MUST begin with Upper Or lowercase character.
Maximum length is 51
can have underscores in between but no spaces any where
cannot end with underscore


Valid
=======
John_Smith
John
JOHN
J129
J129_89
J129_89_aBC

Invalid
=========
J__33 == has two underscores continuously
J__33_ == ends with underscore

TIA
Niels Ull
11/6/2007 8:14:40 AM
[quoted text, click to view]

How about:
^[A-Za-z][A-Za-z0-9]*(_[A-Za-z0-9]+)*$

That should take care of everything but the length requirement. You may be
able to get that working as well, using something like

^[A-Za-z]([A-Za-z0-9]|(_(?=[A-Za-z0-9])){0,50}$

but that is a bit more tricky.

Note: I haven't tested these!

Jesse Houwing
11/6/2007 9:36:32 AM
Hello slg,

Not that hard is it?

[A-Za-z](_?[A-Za-z0-9])*

guessing that a one character sting is Ok as well. if not, make the * at
the end a +.

Checking for a strings length is something that String.Lentgh was designed
for. Or where you can use the MaxLength of a textbox.

Jesse

[quoted text, click to view]
--
Jesse Houwing
jesse.houwing at sogeti.nl

AddThis Social Bookmark Button