Kingsley
Kingsley

Reputation: 365

Regular Expressions to restrict specific user input

I want to restrict users to enter data in the form Hello World... I want to use regular expressions but I am not good at it.

My attempt was: ^([A-Z]{1})([a-z]{1,})([ ])?([A-Z]{1})?([a-z]{1,})?$

For the groups starting at ([ ])? Are supposed to be optional...

For instance, the following are valid entries:

Hello, Hello World, People, People Talk

The following are invalid:

people, people Talk, People talk, people talk, heLlo

This REGEX would have to be case-sensative as the previous examples imply.

Upvotes: 1

Views: 466

Answers (1)

Barmar
Barmar

Reputation: 780724

You should make the whole second word optional as a single group, rather than putting ? after each part of it. Otherwise, the space between the words is optional, so you'll allow two words with no space between them, and the initial capital letter is optional, so you'll allow Hello world.

^[A-Z][a-z]+(\s[A-Z][a-z]+)?$

There's no need for {1} as patterns match a single time by default. + is normally used to match 1 or more of something, rather than {1,}. And \s matches any kind of whitespace.

And you need to anchor the regexp with ^ and $ so the entire input has to match it.

Upvotes: 3

Related Questions