0

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
1
  • Don't forget to start your RegEx with ^ to signify the start of the string. Commented May 5, 2010 at 11:55

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.