Instantly share code, notes, and snippets.

Embed
What would you like to do?
Minimal example of handling escape characters.
fn main() {
for arg in std::env::args().skip(1) {
println!("{}", unescape(arg.as_ref()));
}
}
/// Takes a string and replaces escape sequences with the characters they represent.
fn unescape(data: &str) -> String {
let mut result = String::with_capacity(data.len());
let mut iterator = data.chars();
while let Some(c) = iterator.next() {
// Push character and continue if it's not the start of an escape sequence.
if c != '\\' {
result.push(c);
continue;
}
// Otherwise, match the next char.
if let Some(next) = iterator.next() {
let escaped = match next {
'\'' => Some('\''),
'\"' => Some('\"'),
'n' => Some('\n'),
'r' => Some('\r'),
't' => Some('\t'),
'0' => Some('\0'),
_ => None,
};
if let Some(escaped) = escaped {
// Push the escaped char instead.
result.push(escaped);
} else {
// Just push unrecognized escape sequences
result.push(c);
result.push(next);
}
} else {
result.push(c);
}
}
result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment