How to Convert Camelcase into Human-Readable Names in Java

How do I convert CamelCase into human-readable names in Java?

This works with your testcases:

static String splitCamelCase(String s) {
return s.replaceAll(
String.format("%s|%s|%s",
"(?<=[A-Z])(?=[A-Z][a-z])",
"(?<=[^A-Z])(?=[A-Z])",
"(?<=[A-Za-z])(?=[^A-Za-z])"
),
" "
);
}

Here's a test harness:

    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) + "]");
}

It uses zero-length matching regex with lookbehind and lookforward to find where to insert spaces. Basically there are 3 patterns, and I use String.format to put them together to make it more readable.

The three patterns are:

UC behind me, UC followed by LC in front of me

  XMLParser   AString    PDFLoader
/\ /\ /\

non-UC behind me, UC in front of me

 MyClass   99Bottles
/\ /\

Letter behind me, non-letter in front of me

 GL11    May5    BFG9000
/\ /\ /\

References

  • regular-expressions.info/Lookarounds

Related questions

Using zero-length matching lookarounds to split:

  • Regex split string but keep separators
  • Java split is eating my characters

How do I convert underscore into human-readable names in Java?

A naive way of accomplishing this would be to replace every '_' with a ' ', and then trim the whitespaces off the final string:

public static String splitUnderscore(String s) {
return s.replace("_", " ").trim();
}

While the above works for most cases, to handle multiple adjacent underscores we could use a regular expression to replace any number of consecutive underscores with a single ' ':

public static String splitUnderscore(String s) {
return s.replaceAll("_{1,}", " ").trim();
}

How do I convert CamelCase into human-readable Title Case in VBScript?

Probably an easier way to do this, but this should give you the results you're looking for.

MsgBox SplitCamelCase ("lowercase")         ' Returns: "lowercase"
MsgBox SplitCamelCase ("Class") ' Returns: "Class"
MsgBox SplitCamelCase ("My Class") ' Returns: "My Class"
MsgBox SplitCamelCase ("HTML") ' Returns: "HTML"
MsgBox SplitCamelCase ("PDF Loader") ' Returns: "PDF Loader"
MsgBox SplitCamelCase ("A String") ' Returns: "A String"
MsgBox SplitCamelCase ("Simple XML Parser") ' Returns: "Simple XML Parser"
MsgBox SplitCamelCase ("GL 11 Version") ' Returns: "GL 11 Version"
MsgBox SplitCamelCase ("CSDVersionCamel") ' Returns: "CSD Version Camel"

Function SplitCamelCase(strTxt)
Dim strNew, i

strNew = ""

For i = 1 To Len(strTxt)

If Mid(strTxt, i, 1) = " " Then
strNew = strNew & Mid(strTxt, i, 1)
ElseIf IsNumeric(Mid(strTxt, i, 1)) Then
If i > 1 Then
If IsNumeric(Mid(strTxt, i - 1, 1)) Then
strNew = strNew & Mid(strTxt, i, 1)
ElseIf Mid(strTxt, i - 1, 1) = " " Then
strNew = strNew & Mid(strTxt, i, 1)
Else
strNew = strNew & " " & Mid(strTxt, i, 1)
End If
Else
strNew = strNew & " " & Mid(strTxt, i, 1)
End If
ElseIf Mid(strTxt, i, 1) = UCase(Mid(strTxt, i, 1)) Then
If i > 1 Then
If Mid(strTxt, i - 1, 1) = UCase(Mid(strTxt, i - 1, 1)) Then
If Mid(strTxt, i + 1, 1) = " " Then
strNew = strNew & Mid(strTxt, i, 1)
ElseIf Mid(strTxt, i + 1, 1) = "" Then
strNew = strNew & Mid(strTxt, i, 1)
ElseIf IsNumeric(Mid(strTxt, i + 1, 1)) = True Then
strNew = strNew & Mid(strTxt, i, 1)
ElseIf Mid(strTxt, i + 1, 1) = LCase(Mid(strTxt, i + 1, 1)) Then
If Mid(strTxt, i - 1, 1) = " " Then
strNew = strNew & Mid(strTxt, i, 1)
Else
strNew = strNew & " " & Mid(strTxt, i, 1)
End If
Else
strNew = strNew & Mid(strTxt, i, 1)
End If
ElseIf Mid(strTxt, i - 1, 1) <> " " Then
strNew = strNew & " " & Mid(strTxt, i, 1)
Else
strNew = strNew & Mid(strTxt, i, 1)
End If
Else
strNew = strNew & Mid(strTxt, i, 1)
End If
Else
strNew = strNew & Mid(strTxt, i, 1)
End If
Next

SplitCamelCase = Trim(strNew)

End Function

What is the simplest way to convert a Java string from all caps (words separated by underscores) to CamelCase (no word separators)?

Another option is using Google Guava's com.google.common.base.CaseFormat

George Hawkins left a comment with this example of usage:

CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, "THIS_IS_AN_EXAMPLE_STRING");

Regex for converting CamelCase to camel_case in java

See this question and CaseFormat from guava

in your case, something like:

CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, "SomeInput");

Need to convert underscore separated words into human readable form?

Using java-8 you can do so in a single line :

String str = "NAME_OF_THINGS";

Arrays.stream(str.replaceAll("_", " ").toLowerCase().split(" "))
.map(s -> Character.toUpperCase(s.charAt(0)) + s.substring(1) + " ")
.forEach(System.out::print);

Here we replace all occurences of _ with " " and then convert the entire string to lowercase. Next we split it based on " " and then perform sub-string operation to achieve the result.

This gives the output :

Name Of Things

To get only the first letter capitalized use:

String newString = Character.toUpperCase(str.charAt(0)) + str.substring(1)
.replaceAll("_", " ").toLowerCase();

This gives :

Name of things

Convert camelCaseText to Title Case Text

const text = 'helloThereMister';
const result = text.replace(/([A-Z])/g, " $1");
const finalResult = result.charAt(0).toUpperCase() + result.slice(1);
console.log(finalResult);

How can I convert camelCase to a string with spaces? (e.g. camelCase to Camel Case)

#rereplace("camelCaseString","([A-Z])"," \1","all")#

edit: the version below will handle the lowercase first character.

#rereplace(rereplace("camelCaseString","(^[a-z])","\u\1"),"([A-Z])"," \1","all")#

How do I convert a camelCase string to underscore in java keeping some upper cases and the rests as lower cases?

You can use Matcher#appendReplacement and pass dynamic replacement, based on what was found by regex.

I also changed your regex a little bit, to not include lowercase part in match, but accept only uppercase character which is preceded by lowercase character. More info at: http://www.regular-expressions.info/lookaround.html

String text = "Hi How areYouToday";
Matcher m = Pattern.compile("(?<=[a-z])[A-Z]").matcher(text);

StringBuffer sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, "_"+m.group().toLowerCase());
}
m.appendTail(sb);

System.out.println(sb.toString()); //Hi How are_you_today

OR Since Java 9

Matcher m = Pattern.compile("(?<=[a-z])[A-Z]").matcher(text);
String result = m.replaceAll(match -> "_" + match.group().toLowerCase());

because construct

StringBuffer sb = new StringBuffer();
while(m.find()){
m.appendReplacement(sb, /*replacement for each match*/);
}
m.appendTail(sb);
String result = sb.toString();

was wrapped into Matcher#replaceAll​(Function replacer) so it can be used as

String result = m.replaceAll( (MatchResult match) -> /*replacement for each match*/ );

How to convert camelCase to Camel Case?

"thisStringIsGood"
// insert a space before all caps
.replace(/([A-Z])/g, ' $1')
// uppercase the first character
.replace(/^./, function(str){ return str.toUpperCase(); })

displays

This String Is Good

(function() {
const textbox = document.querySelector('#textbox') const result = document.querySelector('#result') function split() { result.innerText = textbox.value // insert a space before all caps .replace(/([A-Z])/g, ' $1') // uppercase the first character .replace(/^./, (str) => str.toUpperCase()) };
textbox.addEventListener('input', split); split();}());
#result {  margin-top: 1em;  padding: .5em;  background: #eee;  white-space: pre;}
<div>  Text to split  <input id="textbox" value="thisStringIsGood" /></div>
<div id="result"></div>


Related Topics



Leave a reply



Submit