views:

427

answers:

3

I have coded the next function. But surely someone has a more elegant way to perform this task.

/**
 * 
 * HTML 4 Specification
 * ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number 
 * of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").
 * @param s
 * @return
 */
public static String sanitizeHTMLIdAttribute(String s) {
  String sanitize = "";
  if(s!=null) {
    for(int i = 0; i < s.length(); i++) {
      if(s.charAt(i) == '-' || s.charAt(i) == '_' || s.charAt(i) == ':' || 
         s.charAt(i) == '.' || s.charAt(i) == '0' || s.charAt(i) == '1' || 
         s.charAt(i) == '2' || s.charAt(i) == '3' || s.charAt(i) == '4' || 
         s.charAt(i) == '5' || s.charAt(i) == '6' || s.charAt(i) == '7' || 
         s.charAt(i) == '8' || s.charAt(i) == '9' || 
         s.charAt(i) == 'a' || s.charAt(i) == 'b' || s.charAt(i) == 'c' || 
         s.charAt(i) == 'd' || s.charAt(i) == 'e' || s.charAt(i) == 'f' || 
         s.charAt(i) == 'g' || s.charAt(i) == 'h' || s.charAt(i) == 'i' || 
         s.charAt(i) == 'j' || s.charAt(i) == 'k' || s.charAt(i) == 'l' ||  
         s.charAt(i) == 'm' || s.charAt(i) == 'n' || s.charAt(i) == 'o' ||
         s.charAt(i) == 'p' || s.charAt(i) == 'q' || s.charAt(i) == 'r' || 
         s.charAt(i) == 's' || s.charAt(i) == 't' || s.charAt(i) == 'u' || 
         s.charAt(i) == 'w' || s.charAt(i) == 'x' || s.charAt(i) == 'y' ||
     s.charAt(i) == 'z' || 
         s.charAt(i) == 'A' || s.charAt(i) == 'B' || s.charAt(i) == 'C' || 
         s.charAt(i) == 'D' || s.charAt(i) == 'E' || s.charAt(i) == 'F' || 
         s.charAt(i) == 'G' || s.charAt(i) == 'H' || s.charAt(i) == 'I' ||
         s.charAt(i) == 'J' || s.charAt(i) == 'K' || s.charAt(i) == 'L' ||
         s.charAt(i) == 'M' || s.charAt(i) == 'N' || s.charAt(i) == 'O' ||
         s.charAt(i) == 'P' || s.charAt(i) == 'Q' || s.charAt(i) == 'R' || 
         s.charAt(i) == 'S' || s.charAt(i) == 'T' || s.charAt(i) == 'U' || 
         s.charAt(i) == 'W' ||  s.charAt(i) == 'X' || s.charAt(i) == 'Y' || 
         s.charAt(i) == 'Z') {
              sanitize += s.charAt(i);
      }
    }
    if(sanitize.length()>0) {
      while(sanitize.charAt(0) == '0' || sanitize.charAt(0) == '1' || 
            sanitize.charAt(0) == '2' || sanitize.charAt(0) == '3' || 
            sanitize.charAt(0) == '4' || sanitize.charAt(0) == '5' || 
            sanitize.charAt(0) == '6' || sanitize.charAt(0) == '7' || 
            sanitize.charAt(0) == '8' || sanitize.charAt(0) == '9') {
                sanitize = sanitize.substring(1, sanitize.length()); 
      }
    }
    return sanitize;
  } 
  return null;   
}
A: 

You could significantly shorten your code by using Character.isLetterOrDigit(char); e.g.

for(int i = 0; i < s.length(); i++) {
  char c = s.charAt(i);

  if (Character.isLetterOrDigit(c) || c == '.' || etc ...) {

  }
}

You could do this in conjunction with storing the permitted punctuation characters in a Set; e.g.

private static final Set<Character> ALLOWED =
  new HashSet<Character>(Arrays.asList('.', '-', '_', ':'));

for(int i = 0; i < s.length(); i++) {
  char c = s.charAt(i);

  if (ALLOWED.contains(c)) {

  }
}
Adamski
FYI: the character e-acute `'\u00e9'` is a letter or digit, but not a valid HTML identifier. That method will return true for a wide range of Unicode characters.
McDowell
A: 

You might want to check the expressions (regex isn't my forte), but this should drop invalid characters:

  private static Pattern INVALID_LEADING = Pattern.compile("^[^a-zA-Z]+");
  private static Pattern INVALID = Pattern
      .compile("[^\\w\\u002e\\u003a\\u002d\\u005f]+");

  private static String sanitize(String id) {
    Matcher matcher = INVALID_LEADING.matcher(id);
    if (matcher.find()) {
      id = matcher.replaceFirst("");
    }
    Matcher invalid = INVALID.matcher(id);
    if (invalid.find()) {
      id = invalid.replaceAll("");
    }
    return id;
  }

If you aren't happy with regex, be aware that many of your characters are in contiguous ranges, so can be detected with methods like this:

  private static boolean isLatinDigit(char ch) {
    return ch >= '0' && ch <= '9';
  }
McDowell
+1  A: 

I would do something like this:

/**
 * 
 * HTML 4 Specification ID and NAME tokens must begin with a letter
 * ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]),
 * hyphens ("-"), underscores ("_"), colons (":"), and periods (".").
 * 
 * @param s
 * @return
 */
public static String sanitizeHTMLIdAttribute(String s) {
 if (s == null) return null;
 StringBuilder sb = new StringBuilder();
 int firstLegal = 0;
 while (firstLegal < s.length() && !isAZ(s.charAt(firstLegal)))
  ++firstLegal;
 for (int i = firstLegal; i < s.length(); ++i){
  final char ch = s.charAt(i);
  if (isOkIdInnerChar(ch)) sb.append(ch);
 }
 return sb.length() == s.length()? s : sb.toString();
}

private static boolean isOkIdInnerChar(char ch) {
 return isAZ(ch) || isNum(ch) || isSpecial(ch);
}

private static boolean isSpecial(char ch) {
 switch (ch) {
 case '-': case '_':
 case ':': case '.':
  return true;
 default:
  return false;
 }
}

private static boolean isAZ(char ch) {
 return ('A' <= ch && ch <= 'Z') || ('a' <= ch && ch <= 'z'); 
}

private static boolean isNum(char ch) {
 return '0' <= ch && ch <= '9';
}

... except that I'd probably prefer to throw an NullPointerException if s == null, and IllegalArgumentException if s contains no legal characters, but that's a matter of preference, of course. Some extra features:

  • If s is a valid ID, it's returned as-is to save space (fewer string instances floating around) and time (String construction is expensive -- yes, I know allocation is cheap, but there's more going on there than allocation).
  • I don't use Character.isDigit 'cause it returns true for all Unicode digits, including stuff like "٣"
  • I don't use Character.isLetter 'cause it returns true for all Unicode letters, including stuff like "å"
gustafc