Capstone
Capstone

Reputation: 2282

How to remove escaped double-quotes inside a string in Common Lisp?

Running (cl-json:encode-json-to-string 'ctx) gives "\"ctx\""

I need "ctx" not "\"ctx\"".

I could use cl-ppcre and remove matching double-quotes inside the string. However, this seems like overkill. Is there any other way to do this?

Upvotes: 1

Views: 1599

Answers (1)

Rainer Joswig
Rainer Joswig

Reputation: 139261

What does gives "\"ctx\"" mean?

Common Lisp uses the \ as a escape character during printing results.

The string itself has five characters:

CL-USER 12 > (describe "\"ctx\"")

"\"ctx\"" is a SIMPLE-BASE-STRING
0      #\"
1      #\c
2      #\t
3      #\x
4      #\"

You can print the string contents:

CL-USER 11 > (write-string "\"ctx\"")
"ctx"
"\"ctx\""

You can also remove the first and last characters:

CL-USER 10 > (subseq "\"ctx\"" 1 (- 6 2))
"ctx"

You can also trim all surrounding " characters:

CL-USER 13 > (string-trim "\"" "\"ctx\"")
"ctx"

CL-USER 14 > (string-trim '(#\") "\"ctx\"")
"ctx"

String trim takes a sequence of characters as the first argument: the characters to remove. The second argument is the string.

Note that it will remove all such characters from front and back:

CL-USER 15 > (string-trim "\"" "\"\"\"\"ctx\"\"\"\"\"\"\"")
"ctx"

Upvotes: 5

Related Questions