tags:

views:

71

answers:

3

Can someone tell me what the syntax for a regex would be that would only allow the following characters:

  • a-z (lower case only)
  • 0-9
  • period, dash, underscore

Additionally the string must start with only a lower case letter (a-z) and cannot contain any spaces or other characters than listed above.

Thank you in advance for the help, Justin

+5  A: 

You can do: "^[a-z][-a-z0-9\._]*$"

Here is the breakdown

  • ^ beginning of line
  • [a-z] character class for lower values, to match the first letter
  • [-a-z0-9\._] character class for the rest of the required value
  • * zero or more for the last class
  • $ end of String
notnoop
this is wrong. won't match dash, instead you have a range from dot to underscore.
just somebody
When I use this regex with the following string: "test", I get this error: "preg_match() [function.preg-match]: No ending delimiter '^' found"Any idea what this means?
Justin
`*` is zero or more repetitions, not one or more.
Laurence Gonsalves
@Laurence Yes * is zero or more. Thanks
notnoop
Justin: try putting slashes at the beginning and end of the string. eg: `"/^[a-z][a-z0-9\.\-_]*$/"`
Laurence Gonsalves
What regex flavor requires you to escape `[.]`?
Roger Pate
with that backslash it's ok. did i miss it or was the answer edited?
just somebody
That worked with the slashes. Thanks for all the help guys.
Justin
The `.` and `-` inside `[]` doesn't need escaping, but it works either way. `[\.\-]` is the same as `[.-]`.
Jonas
A: 
^[a-z][a-z0-9._\s-]*
Dmitry
this is wrong. won't match dash, which must be either the first or last in the class to be taken literally.
just somebody
fixed, thanks for noticing
Dmitry
+1  A: 
[-._a-z0-9]

or

[-.[:lower:][:digit:]]

or ...

depends on which version of regular expressions you aim for.

just somebody
I will be using this with preg_match in php.
Justin
then it's /^[a-z][-._a-z0-9]*$/
just somebody