Mr Lord
Mr Lord

Reputation: 150

Regex allow letters only and option for one space only

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

Answers (2)

Tim Biegeleisen
Tim Biegeleisen

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.

Demo

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.

Demo

Upvotes: 1

Michael A. Schaffrath
Michael A. Schaffrath

Reputation: 2110

You may use

^[a-zA-Z]*(\s[a-zA-Z]*)?$

See the regex demo

Upvotes: 1

Related Questions