| Thread overview | |||||
|---|---|---|---|---|---|
|
April 20, 2014 string -> string literal | ||||
|---|---|---|---|---|
| ||||
is there a function in phobos anywhere that takes a string and escapes it into a string literal suitable for string mixins? something like
assert (f("abc\ndef") == "\"abc\\ndef\"");
| ||||
April 20, 2014 Re: string -> string literal | ||||
|---|---|---|---|---|
| ||||
Posted in reply to Ellery Newcomer | On Sunday, 20 April 2014 at 17:55:25 UTC, Ellery Newcomer wrote:
> is there a function in phobos anywhere that takes a string and escapes it into a string literal suitable for string mixins? something like
>
> assert (f("abc\ndef") == "\"abc\\ndef\"");
It's a bit hackish, but it avoids deploying code and reinventing anything. You can use format "string-range" formating to print the string escaped. Catch that, and then do it again:
string s = "abc\ndef";
writefln("[%s]\n", s); //raw
s = format("%(%s%)", [s]);
writefln("[%s]\n", s); //escaped
s = format("%(%s%)", [s]);
writefln("[%s]\n", s); //escapes are escaped
As you can see from the output, after two iterations:
[abc
def]
["abc\ndef"]
["\"abc\\ndef\""]
I seem to recall that printing strings "escaped" has been requested before, but, AFAIK, this is the best we are currently providing.
Unless you call std.format's "formatElement" directly. However, this is an internal and undocumented function, and the fact it isn't private is probably an oversight.
| |||
April 22, 2014 Re: string -> string literal | ||||
|---|---|---|---|---|
| ||||
Posted in reply to monarch_dodra Attachments:
| does that work?
string escapeD(string a){
import std.array:replace;
return `r"`~a.replace(`"`,`" "\"" r"`)~`"`;
}
On Sun, Apr 20, 2014 at 11:14 AM, monarch_dodra via Digitalmars-d-learn < digitalmars-d-learn@puremagic.com> wrote:
> On Sunday, 20 April 2014 at 17:55:25 UTC, Ellery Newcomer wrote:
>
>> is there a function in phobos anywhere that takes a string and escapes it into a string literal suitable for string mixins? something like
>>
>> assert (f("abc\ndef") == "\"abc\\ndef\"");
>>
>
> It's a bit hackish, but it avoids deploying code and reinventing anything. You can use format "string-range" formating to print the string escaped. Catch that, and then do it again:
>
> string s = "abc\ndef";
> writefln("[%s]\n", s); //raw
>
> s = format("%(%s%)", [s]);
> writefln("[%s]\n", s); //escaped
>
> s = format("%(%s%)", [s]);
> writefln("[%s]\n", s); //escapes are escaped
>
> As you can see from the output, after two iterations:
>
> [abc
> def]
>
> ["abc\ndef"]
>
> ["\"abc\\ndef\""]
>
> I seem to recall that printing strings "escaped" has been requested before, but, AFAIK, this is the best we are currently providing.
>
> Unless you call std.format's "formatElement" directly. However, this is an internal and undocumented function, and the fact it isn't private is probably an oversight.
>
| |||
Copyright © 1999-2021 by the D Language Foundation
Permalink
Reply