Helper method to replace camel casing with spaces between words using regex. - Java java.lang

Java examples for java.lang:String Camel Case

Description

Helper method to replace camel casing with spaces between words using regex.

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String s = "java2s.com";
        System.out.println(splitCamelCase(s));
    }//from   w w  w. j av a2  s.com

    /**
     * Helper method to replace camel casing with spaces between words. Regex found from NPE on StackOverflow.
     * 
     * @param s String in camelCase form
     * @return String with spaces instead of camelCase
     */
    public static String splitCamelCase(String s) {
        String[] wordSplit = s
                .split("(?<!(^|[A-Z]))(?=[A-Z])|(?<!^)(?=[A-Z][a-z])");
        String newWord = "";
        for (String w : wordSplit) {
            newWord += w + " ";
        }
        return newWord.trim();
    }
}

Related Tutorials