Split Pascalcase String

· · Programming/Code

Do you ever need to split a camel case or pascal case string to a set of words? This can be achieved simply by regular expressions in Java as well as C#. The following code is for Java:

		    String camelCase = "StructuralDesignPattern";
		    StringBuffer label = new StringBuffer(camelCase + 10);
		    java.util.regex.Pattern p = java.util.regex.Pattern.compile("[A-Z][a-z]+");
		    java.util.regex.Matcher m = p.matcher(camelCase);
		    while ( m.find() )
		    {
			label.append( m.group() + " ");
		    }
		    System.out.println(camelCase + " >> " + label.toString());

[ Note: this does not work for all test cases. You may also want to try regexp as “[A-Z][a-z]+”, for matching any continues uppercase letters too (e.g. AnkitJainFROMIndia >> Ankit Jain FROMIndia) ]

Jon Galloway points out a tricky method for C#.

Tags: java, regexp, code

← All posts