Jarosław Kaznodzieja
Jarosław Kaznodzieja

Reputation: 21

RegEx for matching specific upper and lower case patterns

I need to check correctness of input string using regex pattern, every word should start with capital letter, also at the end there could be expression separated with "-". String should contain at least two words or expression with dash.

e.g.

correct:

incorrect:

Pattern pattern = Pattern.compile("([A-Z][a-z]++ )*([A-Z][a-z]++-[A-Z][a-z]++)");
pattern.matcher("Apple Banana Couonut-Dates").matches();

For input "Apple Banana Couonut-Dates" my expression returns false

Upvotes: 2

Views: 507

Answers (1)

The fourth bird
The fourth bird

Reputation: 163217

To match at least 2 uppercase words with an optional part with expression separated with - at the end or a single expression separated with - you might use:

^(?:[A-Z][a-z]+(?: [A-Z][a-z]+\b(?!-))+(?: [A-Z][a-z]+-[A-Z][a-z]+)?|(?:[A-Z][a-z]+ )?[A-Z][a-z]+-[A-Z][a-z]+)$
  • ^ Start of string
  • (?:Non capturing group
    • [A-Z][a-z]+ Match uppercased word
    • (?: [A-Z][a-z]+\b(?!-))+ Repeat 1+ times uppercased word asserting what is on the right is not a -
    • (?: [A-Z][a-z]+-[A-Z][a-z]+)? Optional part, match space and uppercaseword-uppercase word
    • | Or
    • (?:[A-Z][a-z]+ )? Match optional uppercased word with space
    • [A-Z][a-z]+-[A-Z][a-z]+
  • )$ End of string

Regex demo

Note in Java to double escape the backslash.

Upvotes: 1

Related Questions