Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This works with your testcases:</p> <pre><code>static String splitCamelCase(String s) { return s.replaceAll( String.format("%s|%s|%s", "(?&lt;=[A-Z])(?=[A-Z][a-z])", "(?&lt;=[^A-Z])(?=[A-Z])", "(?&lt;=[A-Za-z])(?=[^A-Za-z])" ), " " ); } </code></pre> <p>Here's a test harness:</p> <pre><code> String[] tests = { "lowercase", // [lowercase] "Class", // [Class] "MyClass", // [My Class] "HTML", // [HTML] "PDFLoader", // [PDF Loader] "AString", // [A String] "SimpleXMLParser", // [Simple XML Parser] "GL11Version", // [GL 11 Version] "99Bottles", // [99 Bottles] "May5", // [May 5] "BFG9000", // [BFG 9000] }; for (String test : tests) { System.out.println("[" + splitCamelCase(test) + "]"); } </code></pre> <p>It uses zero-length matching regex with lookbehind and lookforward to find where to insert spaces. Basically there are 3 patterns, and I use <code>String.format</code> to put them together to make it more readable.</p> <p>The three patterns are:</p> <h3>UC behind me, UC followed by LC in front of me</h3> <pre><code> XMLParser AString PDFLoader /\ /\ /\ </code></pre> <h3>non-UC behind me, UC in front of me</h3> <pre><code> MyClass 99Bottles /\ /\ </code></pre> <h3>Letter behind me, non-letter in front of me</h3> <pre><code> GL11 May5 BFG9000 /\ /\ /\ </code></pre> <hr> <h3>References</h3> <ul> <li><a href="http://www.regular-expressions.info/lookaround.html" rel="noreferrer">regular-expressions.info/Lookarounds</a></li> </ul> <h3>Related questions</h3> <p>Using zero-length matching lookarounds to split:</p> <ul> <li><a href="https://stackoverflow.com/questions/2910536/regex-split-string-but-keep-separators">Regex split string but keep separators</a></li> <li><a href="https://stackoverflow.com/questions/2819933/java-split-is-eating-my-characters/">Java split is eating my characters</a></li> </ul>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload