Escapes the given text such that it can be safely embedded in an ANTLR grammar as keyword (i.e., an in-line token). - Java java.lang

Java examples for java.lang:String Escape

Introduction

The following code shows how to Escapes the given text such that it can be safely embedded in an ANTLR grammar as keyword (i.e., an in-line token).

Demo Code


public class Main {
  public static void main(String[] argv) {
    String value = "java2s.com";
    System.out.println(escapeToANTLRKeyword(value));
  }/*  w ww  .  ja va  2 s. c  o m*/

  /**
   * Escapes the given text such that it can be safely embedded in an ANTLR
   * grammar as keyword (i.e., an in-line token). Single quotes are escaped using
   * a backslash. Backslashes are escaped using a backslash.
   * 
   * @param value
   *          the text to escape
   * 
   * @return the escaped text
   */
  public static String escapeToANTLRKeyword(String value) {
    return escapeToJavaString(value).replace("'", "\\'").replace("%", "\\u0025");
  }

  /**
   * Escapes the given text such that it can be safely embedded in a string
   * literal in Java source code.
   * 
   * @param text
   *          the text to escape
   * 
   * @return the escaped text
   */
  public static String escapeToJavaString(String text) {
    if (text == null) {
      return null;
    }
    String result = text.replaceAll("\\\\", "\\\\\\\\").replaceAll("\"", "\\\\\"").replace("\b", "\\b")
        .replace("\f", "\\f").replace("\n", "\\n").replace("\r", "\\r").replace("\t", "\\t");
    StringBuilder complete = new StringBuilder();
    for (int i = 0; i < result.length(); i++) {
      int codePointI = result.codePointAt(i);
      if (codePointI >= 32 && codePointI <= 127) {
        complete.append(Character.toChars(codePointI));
      } else {
        // use Unicode representation
        complete.append("\\u");
        String hex = Integer.toHexString(codePointI);
        complete.append(getRepeatingString(4 - hex.length(), '0'));
        complete.append(hex);
      }
    }
    return complete.toString();
  }

  public static String getRepeatingString(int count, char character) {
    StringBuilder result = new StringBuilder();
    for (int i = 0; i < count; i++) {
      result.append(character);
    }
    return result.toString();
  }
}

Related Tutorials