Search code examples
regexcapitalize

Regular expression for checking if capital letters are found consecutively in a string


I want to know the regexp for the following case:

The string should contain only alphabetic letters. It must start with a capital letter followed by small letter. Then it can be small letters or capital letters.

^[A-Z][a-z][A-Za-z]*$

But the string must also not contain any consecutive capital letters. How do I add that logic to the regexp?

That is, HttpHandler is correct, but HTTPHandler is wrong.


Solution

  • Take a look at tchrist's answer, especially if you develop for the web or something more "international".

    Oren Trutner's answer isn't quite right (see sample input of "RightHerE" which must be matched, but isn't).

    Here is the correct solution:

    (?!^.*[A-Z]{2,}.*$)^[A-Za-z]*$
    

    Explained:

    (?!^.*[A-Z]{2,}.*$)  // don't match the whole expression if there are two or more consecutive uppercase letters
    ^[A-Za-z]*$          // match uppercase and lowercase letters
    

    /edit

    The key for the solution is a negative lookahead. See: Lookahead and Lookbehind Zero-Length Assertions