Confused
Confused

Reputation: 176

matches() matching words that must start with capitals in Java

So, I've been working with using the method 'matches()' in Java.. as in:

Str1 = 'Jane';
Str1.matches("[A-Z][a-zA-Z]*");

to find whether a string starts with a capital and is followed by any number of big/small letters. I can seem to figure out all the configurations except when I'm trying to match an unknown amount of words. For example if I want to confirm a string is made up of just letters and spaces where each word starts with a capital letter. I was thinking could do

Str2 = 'Jane Marie Doe';
Str2.matches("[A-Z][a-zA-Z\\s]*");

as in a capital followed by any number of spaces, capitals, and lower cases but that wouldn't enforce the rule that every space had to be followed by a capital. Do I need to tokenize(not sure if that's the right word) or split my string up using the spaces as delimiters and then evaluate each word? Or is there a way to enter this into the matches method sort of like ([A-Z][a-zA-Z]\\s)* where the asterisk means any number of the entire entry in parenthesis? Though as I'm typing this I'm thinking that won't even conceptually work because the last word won't have a space after it. Perhaps ([A-Z][a-zA-Z]\\s?)* would work? But, it doesn't. Is there something that will?

I did see that there were some other questions that addressed this but I couldn't seem to find a definitive working answer.

Upvotes: 1

Views: 10036

Answers (4)

user8778656
user8778656

Reputation: 1

This will work

^([A-Z][a-zA-Z]*\s*)+$

Upvotes: 0

Phillip Schmidt
Phillip Schmidt

Reputation: 8818

Try this:

([A-Z][a-zA-Z]*\s*)+

Single capital letter, followed by any number of other letters, followed by any number of spaces, repeated any number of times.

Depending on your situation, you might also want to add in legal punctuation, like hyphens and stuff.

So, something like:

([A-Z][a-zA-Z\-\']*\s*)*

Upvotes: 7

NPE
NPE

Reputation: 500663

Try the following regex:

"[A-Z][a-zA-Z]*(\\s+[A-Z][a-zA-Z]*)*$"

Upvotes: 1

Ted Hopp
Ted Hopp

Reputation: 234847

This should work:

"([A-Z][a-zA-Z]*\\s*)*"

I just changed \\s? to \\s* to allow matching of more than one space between words.

Upvotes: 1

Related Questions