tags:

views:

33

answers:

1

I'm trying to write a a regex to validate a string to match the following rules.

  • Must start with a-z (case insensitive)
  • Must only contain a-z A-Z 0-9 . -

I've put something together based on my limited knowledge and ran it through an online testing tool for a whole bunch of situations and the results were as I had hoped however when I place the pattern into my .NET code it doesn't match correctly.

The pattern I am using is,

[a-zA-Z][a-zA-Z0-9.\-]*

Is this the correct pattern or am I barking up the wrong tree?

Some examples of what I'm expecting.

  • craig.bovis - VALID
  • 24craig - INVALID
  • craig@bovis - INVALID
  • craig24 - VALID
  • -craig24 - INVALID
  • craig24.bovis-test - VALID
+4  A: 

You're close. You need to anchor the match to the beginning and end of the string:

^[a-zA-Z][a-zA-Z0-9.\-]*$

The ^ mean "beginning of string" and $ means "end of string". Without them, the expression will match anywhere within the string as well.

Dean Harding
Thanks, that works a treat.
Craig Bovis