How to escape "# and #" in raw string literals

102 Views Asked by At

I wanna do this

let mystr = r#"
Id("#1#")
Id("#2#")
Id("#3#")
"#;

Which does not compile, since I need to somehow escape the "# and the #" occurences. but I don't know how to...

2

There are 2 best solutions below

2
Milos Stojanovic On BEST ANSWER

So, the problem with your approach is that your raw string contains sequence that is used for terminating raw string. What you need to do is add another # on start and end of raw string. Like this:

let mystr = r##"
Id("#1#")
Id("#2#")
Id("#3#")
"##;

Notice second opening and closing #.
Output is:

Id("#1#")
Id("#2#")
Id("#3#")

You can check it out here on playground.

Check out docs, especially this part:

Raw string literals do not process any escapes. They start with the character U+0072 (r), followed by fewer than 256 of the character U+0023 (#) and a U+0022 (double-quote) character. The raw string body can contain any sequence of Unicode characters and is terminated only by another U+0022 (double-quote) character, followed by the same number of U+0023 (#) characters that preceded the opening U+0022 (double-quote) character.

0
Cerberus On

You can use an arbitrary number of hashes as string delimiters, as long as this number of hashes don't appear in the string itself. Like this:

let mystr = r##"
    Id("#1#")
    Id("#2#")
    Id("#3#")
"##;