Created
August 26, 2019 11:04
-
-
Save basinilya/8b3ab8e0f5eebc7e3db8bb09ca70c856 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class EclipseExtractConstant { | |
private static final int _42 = 42; | |
private static final String STRING€WITH_SPECIAL_CHARACTERS = "string€with%special†characters/\\!"; | |
private static final String _100STRINGSSTARTSWITHNUMBER = "100stringsstartswithnumber"; | |
private static final String STRING_WITH_SPACES = "string with spaces"; | |
public static void main(final String[] args) { | |
System.out.println(x(STRING€WITH_SPECIAL_CHARACTERS)); | |
System.out.println(x(_100STRINGSSTARTSWITHNUMBER)); | |
System.out.println(x(STRING_WITH_SPACES)); | |
} | |
// https://git.eclipse.org/c/jdt/eclipse.jdt.ui.git/tree/org.eclipse.jdt.ui/core%20extension/org/eclipse/jdt/internal/corext/codemanipulation/StubUtility.java?id=c25e5a83e3a015ddf6bfbef854ccc96a816cf267#n1132 | |
static String x(final String string) { | |
final StringBuilder res = new StringBuilder(); | |
boolean needsUnderscore = false; | |
for (int i = 0; i < string.length(); i++) { | |
final char ch = string.charAt(i); | |
if (Character.isJavaIdentifierPart(ch)) { | |
if (res.length() == 0 && !Character.isJavaIdentifierStart(ch) || needsUnderscore) { | |
res.append('_'); | |
} | |
res.append(ch); | |
needsUnderscore = false; | |
} else { | |
needsUnderscore = res.length() > 0; | |
} | |
} | |
if (res.length() > 0) { | |
return res.toString(); | |
} | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment