How do I replace specific characters idiomatically in Rust?

RegexRust

Regex Problem Overview


So I have the string "Hello World!" and want to replace the "!" with "?" so that the new string is "Hello World?"

In Ruby we can do this easily with the gsub method:

"Hello World!".gsub("!", "?")

How to do this idiomatically in Rust?

Regex Solutions


Solution 1 - Regex

You can replace all occurrences of one string within another with str::replace:

let result = str::replace("Hello World!", "!", "?");
// Equivalently:
result = "Hello World!".replace("!", "?");
println!("{}", result); // => "Hello World?"

For more complex cases, you can use regex::Regex::replace_all from regex:

use regex::Regex;
let re = Regex::new(r"[A-Za-z]").unwrap();
let result = re.replace_all("Hello World!", "x");
println!("{}", result); // => "xxxxx xxxxx!"

Solution 2 - Regex

Also you can use iterators and match expression:

let s:String = "Hello, world!".chars()
    .map(|x| match x { 
        '!' => '?', 
        'A'..='Z' => 'X', 
        'a'..='z' => 'x',
        _ => x
    }).collect();
println!("{}", s);// Xxxxx, xxxxx?

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionVinView Question on Stackoverflow
Solution 1 - RegexfnyView Answer on Stackoverflow
Solution 2 - RegexaSpexView Answer on Stackoverflow