Skip to content

Instantly share code, notes, and snippets.

@sometowngeek
Last active June 6, 2019 02:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sometowngeek/697c839a1bf1c9ee58be283b1396cf2e to your computer and use it in GitHub Desktop.
Save sometowngeek/697c839a1bf1c9ee58be283b1396cf2e to your computer and use it in GitHub Desktop.
public class SanitizeThat {
public static String sanitizeIntegerToString(String input) {
if (input == null)
return "";
String result = "";
// Rule: Only digits except for "%" and "_"
result = input.replaceAll("[^\\d\\%\\_]", "");
result = stripInvalidWildcards(result);
return result;
}
public static String sanitizeAlphaToString(String input) {
if (input == null)
return "";
String result = "";
// Rule: Only alpha characters except for "%" and "_"
result = input.replaceAll("[^a-zA-Z\\%\\_]", "");
result = stripInvalidWildcards(result);
return result;
}
// This is the one I'm trying to refine.
private static String stripInvalidWildcards(String input) {
if (input == null)
return "";
String illegalPattern1 = "%%";
String illegalPattern2 = "%_%";
String result = input;
while (result.contains(illegalPattern1) || result.contains(illegalPattern2)) {
result = result.replaceAll(illegalPattern1, "%");
result = result.replaceAll(illegalPattern2, "%");
}
if (result.equals("%") || result.equals("_"))
return "";
return result;
}
}
@sometowngeek
Copy link
Author

Updated stripInvalidWildcards() with updated function.

Still needs improvement.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment