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
You’re close. You need to anchor the match to the beginning and end of the string:
The
^mean “beginning of string” and$means “end of string”. Without them, the expression will match anywhere within the string as well.