I need to build a regex that allows only letters and hyphens, but it needs to require the hyphens.
I tried:
^[a-z]+[a-z\-]+[a-z]+$(the match without hyphens pass)([A-Za-z\-]+)(the match without hyphens pass too)[a-zA-Z][\-]+(it didn’t work)
Could someone write it to me?
Thanks in advance.
You need a look ahead:
That little expression
(?=.*-)is a “look ahead”, which is a non-consuming assertion that.*-appears somewhere ahead, which means “there needs to be hyphen in the input”Also, when put first or last the hyphen is a literal hyphen that doesn’t need escaping, otherwise a hyphen denotes a range.