Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matching "camelCase" to a regular expression in java

Tags:

java

regex

String camelCasePattern = "([a-z][A-Z0-9]+)+";

boolean val = "camelCase".matches(camelCasePattern);
System.out.println(val);

The above prints false. I'm trying to match a camelCase pattern starting with lower case letter. I have tried to tweak it a bit, without no luck though. Is the pattern wrong for camelCase?

like image 534
Force444 Avatar asked Dec 19 '22 14:12

Force444


2 Answers

I would go with:

String camelCasePattern = "([a-z]+[A-Z]+\\w+)+"; // 3rd edit, getting better
System.out.println("camelCaseCaseCCase5".matches(camelCasePattern));

Output

true

Your current Pattern is matching one lowercase followed by as many uppercase/digit, many times over, which is why it returns false.

like image 107
Mena Avatar answered Jan 07 '23 11:01

Mena


The best way to match your test case is:

String camelCasePattern = "^[a-z]+([A-Z][a-z0-9]+)+";

This will ensure it starts with a lowecase, and then has a repeating pattern of one capital letter, followed by some lowercase characters

Matches camelCaseTest but not camelCaseDOneWrong

like image 44
Adam Yost Avatar answered Jan 07 '23 12:01

Adam Yost