How to Use Escape Characters in Strings

How to write escape character to string?

In a normal string, you use \\

If this is in a regular expression, it needs to be \\\\

The reason RegEx needs four is because both the String parser and RegEx engine support escapes. Therefore, \\\\ is parsed to \\ by the String parser then to a literal \ by the RegEx parser.

How can I add escape characters to a Java String?

I'm not claiming elegance here, but i think it does what you want it to do (please correct me if I'm mistaken):

public static void main(String[] args)
{
String example = "Hello, I'm\" here";
example = example.replaceAll("'", "\\\\'");
example = example.replaceAll("\"", "\\\\\"");
System.out.println(example);
}

outputs

Hello, I\'m\" here

Add escape \ in front of special character for a string

Decide which special characters you want to escape and just call

query.replace("}", "\\}")

You may keep all special characters you allow in some array then iterate it and replace the occurrences as exemplified.
This method replaces all regex meta characters.

public String escapeMetaCharacters(String inputString){
final String[] metaCharacters = {"\\","^","$","{","}","[","]","(",")",".","*","+","?","|","<",">","-","&","%"};

for (int i = 0 ; i < metaCharacters.length ; i++){
if(inputString.contains(metaCharacters[i])){
inputString = inputString.replace(metaCharacters[i],"\\"+metaCharacters[i]);
}
}
return inputString;
}

You could use it as query=escapeMetaCharacters(query);
Don't think that any library you would find would do anything more than that. At best it defines a complete list of specialCharacters.

Javascript - How to show escape characters in a string?

If your goal is to have

str = "Hello\nWorld";

and output what it contains in string literal form, you can use JSON.stringify:

console.log(JSON.stringify(str)); // ""Hello\nWorld""

const str = "Hello\nWorld";
const json = JSON.stringify(str);
console.log(json); // ""Hello\nWorld""
for (let i = 0; i < json.length; ++i) {
console.log(`${i}: ${json.charAt(i)} (0x${json.charCodeAt(i).toString(16).toUpperCase().padStart(4, "0")})`);
}
.as-console-wrapper {
max-height: 100% !important;
}

How to escape special characters in building a JSON string?

A JSON string must be double-quoted, according to the specs, so you don't need to escape '.

If you have to use special character in your JSON string, you can escape it using \ character.

See this list of special character used in JSON :

\b  Backspace (ascii code 08)
\f Form feed (ascii code 0C)
\n New line
\r Carriage return
\t Tab
\" Double quote
\\ Backslash character


However, even if it is totally contrary to the spec, the author could use \'.

This is bad because :

  • It IS contrary to the specs
  • It is no-longer JSON valid string

But it works, as you want it or not.

For new readers, always use a double quotes for your json strings.

How not to use escape character in java

The problem is that " and \ are both special characters. In order to use them as literals in strings, you need to escape them. So the correct way would be:

str = str.replace("\"", "\\\"");

In this context the strings are broken down as such, with spaces around the characters or clarity:

" \" " This is an escaped quote
" \\ " This is an escaped backslash

Thus if you want to represent a backslash followed by a quote, you can see that is breaks down as:

" \\ \" " Quotes around the whole literal, an escaped backslash, an escaped quote

Storing escape characters in unix variable

The problem is caused by backticks. Use $( ) instead, and it goes away:

var="*a<br>*b<br>*c"
var=$(printf '%s\n' "$var" | sed 's/\*/\\*/g')
printf '%s\n' "$var"

(Why is this problem caused by backticks? Because the only way to nest them is to escape the inner ones with backslashes, so they necessarily change how backslashes behave; whereas $( ), because it uses different starting and ending sigils, can be nested natively).


That said, if your shell is one (like bash) with ksh-inspired extensions, you don't need sed at all here, as the shell can perform simple string replacements natively via parameter expansion:

var="*a<br>*b<br>*c"
printf '%s\n' "${var//'*'/'\*'}"

For background on why this answer uses printf instead of echo, see Why is printf better than echo? at [unix.se], or the APPLICATION USAGE section of the POSIX specification for echo.

How to escape special characters in a char* string in C

It is still unclear why you think the string has "dangerous" chars, but if you want to escape some of them:

const char *str = "my dangerous";
const char *ooh = "aeoui\\";

char buf[BIG_ENOUGH];
size_t bp = 0;

for (size_t sp = 0; str[sp]; sp++) {
if (strchr(ooh, str[sp])) buf[bp++] = '\\';
buf[bp++] = str[sp];
}
buf[bp] = 0;


Related Topics



Leave a reply



Submit