Matching "camelCase" regex in java

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

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

The above value displays false. I am trying to match a camelCase pattern starting with a lowercase letter. I tried to tweak it a bit, but no luck. Is the template incorrect for camelCase?

+4
source share
4 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 Patternone corresponds to one lowercase case, followed by many uppercase / numbers, many times, so it returns false.

+4
source

Assuming that the word "camel's word" is defined as follows:

"The word of a camel" definition:

  • It consists only of upper and lower case letters; [A-Za-z].
  • ; [a-z].
  • ; [a-z].

Java- , :

// TEST.java 20140529_0900
import java.util.regex.*;
public class TEST {
    public static void main(String[] args) {
        String data =   "This has one camelCase word."+
                        "This hasTwo camelCaseWords."+
                        "NON CamelCase withDigits123 words.";
        Pattern re_camel_case_word = Pattern.compile(
            "  # Match one camelCase word.\n" +
            "  \\b       # Anchor to word boundary.                    \n" +
            "  [a-z]+    # Begin with one or more lowercase alphas.    \n" +
            "  (?:       # One or more parts starting with uppercase.  \n" +
            "    [A-Z]   # At least one uppercase alpha                \n" +
            "    [a-z]*  # followed by zero or more lowercase alphas.  \n" +
            "  )+        # One or more parts starting with uppercase.  \n" +
            "  \\b       # Anchor to word boundary.",
            Pattern.COMMENTS);
        Matcher matcher = re_camel_case_word.matcher(data);
        while (matcher.find())
            System.out.println(matcher.group(0));
    }
}

, -- . , " ".

+2

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

+1

:

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

, lowecase, ,

camelCaseTest, camelCaseDOneWrong

+1

Source: https://habr.com/ru/post/1542503/


All Articles