Escape speech marks in regex


#1

How do you escape speech marks " in a regular expression created with regex? The regular expression I’m using is ID is "([0-9a-zA-Z]{4})". I’ve tried using `’ as an escape character, but results in the following compiler error:

src/main.rs:19:51: 19:52 error: unknown start of token: \\
src/main.rs:19     let re = Regex::new(r"ID is \"([0-9a-zA-Z]{4})\"").unwrap();


#2

You are using a raw string. Thus all characters but the closing " (quote) are ignored, even the backslash.

Raw strings have one trick up their sleeve for this: you can prepend hashs (#) and add the same number after the closing quote:

r####"ID is "([0-9a-zA-Z]{4})""####

#3

Thanks. I misunderstood the meaning of the r in r"...". I thought that meant regular expression :slightly_smiling: Using a normal string I can get this working now, but thanks for the # prepending, that’s good to know.