Tuesday, March 1, 2011

Regex for a-z, 0-9, . and -

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

From stackoverflow
  • 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
    just somebody : this is wrong. won't match dash, instead you have a range from dot to underscore.
    Justin : 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?
    Laurence Gonsalves : `*` is zero or more repetitions, not one or more.
    notnoop : @Laurence Yes * is zero or more. Thanks
    Laurence Gonsalves : Justin: try putting slashes at the beginning and end of the string. eg: `"/^[a-z][a-z0-9\.\-_]*$/"`
    Roger Pate : What regex flavor requires you to escape `[.]`?
    just somebody : with that backslash it's ok. did i miss it or was the answer edited?
    Justin : That worked with the slashes. Thanks for all the help guys.
    Jonas : The `.` and `-` inside `[]` doesn't need escaping, but it works either way. `[\.\-]` is the same as `[.-]`.
  • ^[a-z][a-z0-9._\s-]*
    
    just somebody : this is wrong. won't match dash, which must be either the first or last in the class to be taken literally.
    Dmitry : fixed, thanks for noticing
  • [-._a-z0-9]
    

    or

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

    or ...

    depends on which version of regular expressions you aim for.

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

0 comments:

Post a Comment