All Things Techie With Huge, Unstructured, Intuitive Leaps

A Java class to escape illegal characters



Here is a Java Class to escape illegal characters with a static method:



package com.mypackage;

import java.util.HashMap;
import java.util.regex.Pattern;

/**
 * The Class StringHelper.
 */
public class StringHelper {

  /**
* Escapes characters that have special meaning to regular expressions.

* @param s
*            String to be escaped
* @return escaped String
*/
  public static String fixString(String s){


    int length = s.length();
    int newLength = length;
    // first check for characters that might
    // be dangerous and calculate a length
    // of the string that has escapes.
    for (int i=0; i<length; i++){
      char c = s.charAt(i);
      if (!((c>='0' && c<='9') || (c>='A' && c<='Z') || (c>='a' && c<='z'))){
        newLength += 1;
      }
    }
    if (length == newLength){
      // nothing to escape in the string
      return s;
    }
    StringBuffer sb = new StringBuffer(newLength);
    for (int i=0; i<length; i++){
      char c = s.charAt(i);
      if (!((c>='0' && c<='9') || (c>='A' && c<='Z') || (c>='a' && c<='z'))){
        sb.append('\\');
      }
      sb.append(c);
    }
    return sb.toString();
  }
}

Hope this helps someone.

No comments:

Post a Comment