Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the most simple (and correct) escaping algorithm?

Disclaimer: this is theoretical question with the purpose of increasing my understanding. I know that I can always use tools like a JSON library to solve the problem.

Suppose I want to create a comma separated list of values which may themselves contain comma's. These commas need to be escaped first. Assuming that I use . as the escape character then ["a", "b,c"] becomes a,b.,c.

However, if one of the values originally contained a ., sequence then we'd need to escape those before escaping the commas. So [ "a", "b.,c" ] becomes a,b..,c.

However, if one of the values originally contained a .., sequence then we'd need to escape those before escaping the commas. So [ "a", "b..,c" ] becomes a,b...,c.

However, if one of the values originally contained a ..., sequence then we'd need to escape those before escaping the commas. So [ "a", "b...,c" ] becomes a,b....,c.

Etc...

The decoding process must perform the reversed recursion.

However, I suspect if I'm making it too hard and there is a simpler way. Is there a simpler way?

like image 907
StackedCrooked Avatar asked Feb 08 '13 20:02

StackedCrooked


People also ask

What is escaping in coding?

Escaping is a method that allows us to tell a computer to do something special with the text we supply or to ignore the special function of a character. To tell the computer that it should expect an escape character we use a special escape marker, we usually make use of the backslash ().

Why are escape sequence used?

Escape sequences are typically used to specify actions such as carriage returns and tab movements on terminals and printers. They are also used to provide literal representations of nonprinting characters and characters that usually have special meanings, such as the double quotation mark (").


1 Answers

Thanks to @mkbeckish' comment I realized that the algorithm can be implemented as:

// encoding
text.replace(escape, escape + escape);
text.replace(delim , escape + delim);

// decoding
text.replace(escape + delim , delim);
text.replace(escape + escape, escape);

Example implementation.

It's silly that I didn't realize this myself..

like image 146
StackedCrooked Avatar answered Oct 06 '22 03:10

StackedCrooked