Home > OS >  Regex that allows a-z, A-Z, space and hyphen, but does not allow the string to start or end with spa
Regex that allows a-z, A-Z, space and hyphen, but does not allow the string to start or end with spa

Time:05-05

I need to write a regex that allows a-z, A-Z, space and hyphen, but does not allow the string to start or end with space or hyphen.

So far my regex: /^(?!\s)(?!\-)[a-zA-Z\- ] $/ This almost works, preventing a string from starting with a space or hyphen, however I cannot sort out how to prevent it from ending with space or hyphen.

CodePudding user response:

Prevent it from ending with space or hyphen can be converted to Allowing only a-z, A-Z. So I suggest to append [a-zA-Z] to your regex like /^(?!\s)(?!\-)[a-zA-Z\- ] [a-zA-Z]$/ or /^(?!\s)(?!\-)[a-zA-Z\- ]*[a-zA-Z]$/

CodePudding user response:

You can use

/^[a-zA-Z](?:[a-zA-Z -]*[a-zA-Z])?$/

Details:

  • ^ - start of string
  • [a-zA-Z] - a letter
  • (?:[a-zA-Z -]*[a-zA-Z])? - an optional occurrence of zero or more letters, space or - and then a letter
  • $ - end of string.

If you want to add restrictions with lookarounds, you can use

/^(?![ -]|.*[ -]$)[a-zA-Z -] $/

Here, (?![ -]|.*[ -]$) negative lookahead fails the match if there is a space or - immediately to the right of the current location, or any zero or more chars other than line break chars as many as possible and then a space or - at the end of string.

  • Related