I have been trying to create a regex code to validate a string field in a form. below is what is required for the regex code:
The length of the input is bigger than 0 and less/equal to 14;
Only letters a to z (lower case), "-" (dash) and " " (space) are allowed,
The "-" (dash) and " " (space) letters must be entered,
The "-" or the " " letter must not be either the first or the last letter entered,
"-" must not be the immediate neighbour or adjacent (before or after) to a " ",
"-" or " " must not be the immediate neighbour (adjacent) of itself.
if anyone can help me create the code i would be very grateful.
cheers 4d4m
Whee! Help to know the language and regex flavor you're dealing with though. Perl?
/^(?=.{1,14}$)[a-z]+(-[a-z]+ | [a-z]+-)([a-z]+[- ])*[a-z]+$/i
^: Starting at the beginning of the string, this:
(?=.{1,14}$): (ensures that there's 1 to 14 characters and then the end of the string*)
[a-z]+: checks that there is at least one letter
(-[a-z]+ : then a hyphen, letters, and a space
| [a-z]+-): or a space, letters, and a hyphen
([a-z]+[- ])*: then some letters and a hyphen or space (repeated any number of times, or not at all)
[a-z]+$: and finally at least one more letter before the end of the string
/i means case-insensitive.
* Honestly, I'd remove this part and use whatever your language offers to check string length. Like a .length property, strlen function, len() method...