could someone help me out with a piece of regex please? I want to stop the user entering any charachter other than a-z or a hyphen -
Hope someone can help me.
Thanks
could someone help me out with a piece of regex please? I want to stop the user entering any charachter other than a-z or a hyphen -
Hope someone can help me.
Thanks
You can use the regex: ^[a-z-]+$
^
: Start anchor$
: End anchor[..]
: Char classa-z
: any lowercase alphabet-
: a literal hyphen. Hyphen is usually a meta char inside char class but if its present as the first or last char of the char class it is treated literally.+
: Quantifier for one or moreIf you want to allow empty string you can replace +
with *
If the string doesn't match ^[a-z-]*$
, then a disallowed character was entered. This pattern is anchored so that the entire string is considered, and uses a repeated character class (the star specifies zero or more matches, so an empty string will be accepted) to ensure only allowed characters are used.