Search code examples
javaregexcamelcasing

Regex to split Camel case - with Numbers


I want to split a camelCase name to individual names using regex, for performing a spell check.

The split should be as follows:

1) extendedStructureForNUB --> extended, Structure, For, NUB

2) extendedStructureFor2004 --> extended, Structure, For, 2004

Using the answer from the below question , i am able to split for the 1st condition.

Question : RegEx to split camelCase or TitleCase (advanced)

But for a string containing number (2nd condition), it is not returning as per format.

extendedStrctureFor2004 --> extended, Structure, For2004

Please suggest a way by which i can reuse this regex to split numerals also.


Solution

  • public static void main(String[] args) 
    {     
        for (String w : "camelValue".split("(?<!(^|[A-Z0-9]))(?=[A-Z0-9])|(?<!^)(?=[A-Z][a-z])")) {
             System.out.println(w);
        } 
    }
    

    Edit: Correcting the case for UPPER2000UPPER the regex becomes:

    public static void main(String[] args) 
    {     
        for (String w : "camelValue".split("(?<!(^|[A-Z0-9]))(?=[A-Z0-9])|(?<!(^|[^A-Z]))(?=[0-9])|(?<!(^|[^0-9]))(?=[A-Za-z])|(?<!^)(?=[A-Z][a-z])")) {
             System.out.println(w);
        } 
    }