Regular Expressions to restrict specific user input


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,})?$


^([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.


REGEX





Consider this tool
– Michele Lambertucci
2 days ago





Does this do what you want? ^([A-Z]{1})([a-z]{1,})s*(([A-Z]{1})+([a-z]{1,}))?$
– Michele Lambertucci
2 days ago


^([A-Z]{1})([a-z]{1,})s*(([A-Z]{1})+([a-z]{1,}))?$





Just to clarify, you want a regular expression that matches a series of words where each word starts with a captial letter and the rest of the letters are lowercase?
– Adam P
2 days ago





{1} is never needed, that's the default for all expressions. {1,} can be replaced with +.
– Barmar
2 days ago


{1}


{1,}


+





Since the space between the words is optional, this will allow PeopleTalk
– Barmar
2 days ago


PeopleTalk




1 Answer
1



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.


?


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.


{1}


+


{1,}


s



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


^


$





Now this does what I wanted... Thank you!
– Kingsley
2 days ago





As a note, the ? at the end will only allow one or two words total. If you want more than that you may want to change it to either a * or a quantifier such as {0,x}.
– Adam P
2 days ago


?


*


{0,x}





By the way, how can I restrict an input to accept exactly what I specify in the regular expression? I mean, I want Someone to be typed literally as it is.
– Kingsley
2 days ago





Add ^ and $ anchors. I've updated the answer.
– Barmar
2 days ago


^


$






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Comments

Popular posts from this blog

paramiko-expect timeout is happening after executing the command

Export result set on Dbeaver to CSV

Opening a url is failing in Swift