Reputation: 150
I have a regex that check if the input has only a-z and A-Z and spaces.
this is my expretion
/^[a-zA-Z\s]*$
I am trying to allow a-z A-Z and if the user type sapce it will be only one space.
Exapmle:
ACB
=> vaild
adsbc aDb
=> vaild
adbc def gh
=> not vaild
What do I need to change in my regex?
Upvotes: 1
Views: 59
Reputation: 522712
Try this regex:
^[A-Za-z]*[ ]?[A-Za-z]*$
To keep things simple, you want to match either zero or one space, either at the start, in the middle, or at the end, of the entire string. The above regex expresses this.
We could also solve this using a negative lookahead:
^(?!.* .* )[A-Za-z ]*$
This uses an assertion that, from the beginning of the string, two spaces do not appear anywhere. However, I would expect the first solution to perform better.
Upvotes: 1
Reputation: 2110
You may use
^[a-zA-Z]*(\s[a-zA-Z]*)?$
See the regex demo
Upvotes: 1