user3165926
user3165926

Reputation: 93

match whole sentence with regex

I'm trying to match sentences without capital letters with regex in Java:

"Hi this is a test" -> Shouldn't match
"hi thiS is a test" -> Shouldn't match
"hi this is a test" -> Should match

I've tried the following regex, but it also matches my second example ("hi, thiS is a test").

[a-z]+

It seems like it's only looking at the first word of the sentence.

Any help?

Upvotes: 1

Views: 1396

Answers (4)

Mena
Mena

Reputation: 48404

I would actually advise against regex in this case, since you don't seem to employ extended characters.

Instead try to test as following:

myString.equals(myString.toLowerCase());

Upvotes: 1

SierraOscar
SierraOscar

Reputation: 17637

It's not matching because you haven't used a space in the match pattern, so your regex is only matching whole words with no spaces.

try something like ^[a-z ]+$ instead (notice the space is the square brackets) you can also use \s which is shorthand for 'whitespace characters' but this can also include things like line feeds and carriage returns so just be aware.

This pattern does the following:

^ matches the start of a string

[a-z ]+ matches any a-z character or a space, where 1 or more exists.

$ matches the end of the string.

Upvotes: 1

Lucas Trzesniewski
Lucas Trzesniewski

Reputation: 51330

[a-z]+ will match if your string contains any lowercase letter.

If you want to make sure your string doesn't contain uppercase letters, you could use a negative character class: ^[^A-Z]+$

Be aware that this won't handle accentuated characters (like É) though.

To make this work, you can use Unicode properties: ^\P{Lu}+$
\P means is not in Unicode category, and Lu is the uppercase letter that has a lowercase variant category.

Upvotes: 1

vks
vks

Reputation: 67968

^[a-z ]+$

Try this.This will validate the right ones.

Upvotes: 1

Related Questions