-3

I am writing a regular expression which matches a string with the following conditions. if the string does not match, it will prevent the user from typing(in a UI textbox).

  • must have at least one alphabet
  • may start or end with "',-
  • must not have spaces at the start or end
  • may contain numbers
  • may have space in the middle of the string

This is what I have so far. but it allows the text to end with a space.

^["',-]*[a-zA-Z][a-zA-Z0-9"',\ ]*[a-zA-Z0-9"']$ 
Arun Kamalanathan
  • 8,107
  • 4
  • 23
  • 39

1 Answers1

1

You may use the following pattern:

^(?! |.* $)(?=.*[a-zA-Z])[a-zA-Z0-9"',\ \-]+$

Demo.

Breakdown:

  • ^ - Beginning of string.
  • (?! |.* $) - Negative Lookahead: doesn't start or end with a space.
  • (?=.*[a-zA-Z]) - Positive Lookahead: contains at least one letter.
  • [a-zA-Z0-9"',\ \-]+ - Match one or more characters including letters, digits, ", ', -, and a space character.
  • $ - End of string.