How do I "interpret" escaped characters in a string?

kkeey

I want to process a string containing a backslash followed by an escapable character as if they were one character.

let raw = r#"\""#;
let cooked = raw.process_escape_character_magic();

Right now, raw has 2 characters: \ and ". But what I actually want is cooked, which only has one character: ".

How do I get cooked?

I was thinking about using regex, but I feel like there should probably be a better way.

Boiethios

I like using iterators in Rust, and I think that's a perfect usecase:

#[derive(Debug, PartialEq)]
enum MyError {
    EscapeAtEndOfString,
    InvalidEscapedChar(char),
}

struct InterpretEscapedString<'a> {
    s: std::str::Chars<'a>,
}

impl<'a> Iterator for InterpretEscapedString<'a> {
    type Item = Result<char, MyError>;

    fn next(&mut self) -> Option<Self::Item> {
        self.s.next().map(|c| match c {
            '\\' => match self.s.next() {
                None => Err(MyError::EscapeAtEndOfString),
                Some('n') => Ok('\n'),
                Some('\\') => Ok('\\'),
                // etc.
                Some(c) => Err(MyError::InvalidEscapedChar(c)),
            },
            c => Ok(c),
        })
    }
}

fn interpret_escaped_string(s: &str) -> Result<String, MyError> {
    (InterpretEscapedString { s: s.chars() }).collect()
}

fn main() {
    assert_eq!(interpret_escaped_string(r#""#), Ok("".into()));
    assert_eq!(interpret_escaped_string(r#"a"#), Ok("a".into()));
    assert_eq!(interpret_escaped_string(r#"\"#), Err(MyError::EscapeAtEndOfString));
    assert_eq!(interpret_escaped_string(r#"\\"#), Ok("\\".into()));
    assert_eq!(interpret_escaped_string(r#"a\n"#), Ok("a\n".into()));
    assert_eq!(interpret_escaped_string(r#"a\."#), Err(MyError::InvalidEscapedChar('.')));
}

More complete implementation of such a module in the playground.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How do I interpret ASCII values of characters of a string as chars in C?

How do I decode a double backslashed PERLQQ escaped string into Perl characters?

How do I convert a '\x'-escaped string into a list of the corresponding individual characters?

How do I decode a string with escaped unicode?

How do I match escaped characters in groups in Java RegEx

Why do I see escaped characters on the terminal?

How do I deserialize a property containing an escaped JSON string?

how do I create a string with an escaped open parens?

How do I prevent ReadAsStringAsync returning a doubly escaped string?

How to check if all " characters in a string are escaped

How do I grab the last portion of a log string and interpret it as json?

How do I interpret this instruction?

How do i interpret this timestamp

How can I programmatically build a string containing escaped characters to pass as an argument to a function in Python?

How do I split a string into an array of characters?

How do I remove unknown characters in a string?

How do I remove multiple characters in a string

How do I check for string breaking characters?

How do I split a String by Characters in Java?

How to know if a string is already escaped special with special characters?

How do I urlencode all the characters in a string, including safe characters?

How do I substitute characters in a string with other characters?

How do I unescaped, string that has been escaped multiple times in Rust?

Unable to substitute escaped characters in string

String after Escaped Characters in Regex

How do I interpret the output of `cargo bench`?

How do I interpret Spark PCA output?

How do I interpret this python dependency tree?

How do I interpret the vertical line in a plot?