user8812547
user8812547

Reputation:

Every word in the sentence capital letter

I'm trying to write an regex expression for my task. Every word in the sentence starts with a capital letter, the rest is lower case letter.

(^[A-Z]{1}[a-z\s]+)+

e.g.

Java Test - ok

Java test - not ok

JaVa Test - not ok

java Test - not ok

Upvotes: 0

Views: 57

Answers (2)

rprakash
rprakash

Reputation: 510

If there can be single character in any of the words like :

This Is A Test
I Am A Programmer

then you can use :

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

Demo and explanation can be found here

Otherwise If there are always more than one character in every word, you can use :

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

Demo and explanation can be found here.

Upvotes: 0

The fourth bird
The fourth bird

Reputation: 163457

The pattern you tried will also match Java test because the character class [a-z\s]+ repeats 1+ times any of the listed including a space and does not force the second word to start with an uppercase char.

You could repeat the part matching an uppercase char followed by 1+ lower case chars for every iteration.

Note that \s will also match a newline and you can omit {1}

^[A-Z][a-z]+(?: [A-Z][a-z]+)*$
  • ^ Start of string
  • [A-Z][a-z]+ Match 1 uppercase A-Z and 1+ lowercase a-z
  • (?: Non capturing group
    • [A-Z][a-z]+ Match a space, 1 uppercase A-Z and 1+ lowercase chars a-z
  • )* Close non capturing group and repeat 1+ times
  • $ End of string

Regex demo

Instead of matching a single space you could also match 1+ horizonltal whitespace chars using \h (In java \\h)

Regex demo

Upvotes: 1

Related Questions