Skip to content

Instantly share code, notes, and snippets.

@basinilya
Created August 26, 2019 11:04
Show Gist options
  • Save basinilya/8b3ab8e0f5eebc7e3db8bb09ca70c856 to your computer and use it in GitHub Desktop.
Save basinilya/8b3ab8e0f5eebc7e3db8bb09ca70c856 to your computer and use it in GitHub Desktop.
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