Saturday, September 8, 2018

StringEscapeUtils Java Methods to escape Java control chars ,quotes and unescape


StringEscapeUtils.escapeJava()
Escapes the characters in a String using Java String rules.
Deals correctly with quotes and control-chars (tab, backslash, cr, ff, etc.)
So a tab becomes the characters '\\' and 't'.
The only difference between Java strings and JavaScript strings is that in JavaScript, a single quote and forward-slash (/) are escaped.
Example:
input string: He didn't say, "Stop!"
output string: He didn't say, \"Stop!\"
StringEscapeUtils.unescapeJava()
Unescapes any Java literals found in the String. For example,
it will turn a sequence of '\' and 'n' into a newline character,
unless the '\' is preceded by another '\'.
Example Program:

package com.nagaraju.simplejson;

import org.apache.commons.text.StringEscapeUtils;

public class EscapeJavaSpecialChars {
public static void main(String[] args) {
//Case 1: Here we will see the out put as same as input
String string1 = StringEscapeUtils.escapeJava("\n");
System.out.println(string1);
//Case 2: Here we will see that the input \n becomes th new line
String string2 = StringEscapeUtils.unescapeJava("\n");
System.out.println(string2);
String string21="\n";
//Same as Case 2
System.out.println(string21);
//The Case 2 becomes Case 1 because we have used same method.
String string3 = StringEscapeUtils.escapeJava(string2);
System.out.println(string3);
}
}

Output:
\n




\n


No comments:

Post a Comment

Recent Post

Databricks Delta table merge Example

here's some sample code that demonstrates a merge operation on a Delta table using PySpark:   from pyspark.sql import SparkSession # cre...