What I am trying to do: this regex should have to force the first character to be a letter, after that character, letters, a whitespaces or ‘-‘ can be inserted.
This first part works just fine: (^[A-Za-z][A-Za-z -]*$)
Then I would like to allow an empty string as well : (^$)
When I combine the two however, the user can start the string with a whitespace. What am I doing wrong here?
Thanx!
(^[A-Za-z][A-Za-z -]*$)||(^$)
(I don’t know if this info is needed but I use this in Java, as part of a class that extends from InputVerifier, to set verifiers on JTextFields)
The following should do it:
The
?makes the expression inside the parentheses optional.The reason your original regex isn’t quite right is the
||. The regex “or” operator is a single|. Now considerx||y. This matchesxor an empty string ory. Since the empty string isn’t in any way anchored,Pattern.find()will find at least one instance of it in any input.