pub fn string_replace_all<'a, P: Into<Pattern<'a>>>(
input: &str,
pattern: P,
replacement: &str,
) -> StringExpand description
Replaces all occurrences of from with to in input, supporting both exact string and regex replacements.
This function works as follows:
- If
fromis a string slice (&str), it performs a simple.replace()on the input. - If
fromis a regex (Regex), it applies.replace_all()to match the pattern. - The original input string remains unchanged and a new
Stringis returned. - Consecutive occurrences of
toare collapsed into a single instance to avoid unintended duplication.
§Arguments
input- The original string.from- The pattern to replace (either a string slice or a regex).to- The replacement string.
§Returns
A new String with all occurrences replaced. Consecutive duplicates of to are merged.
§Examples
use string_replace_all::string_replace_all;
let text = "Hello world! This is Rust.";
let result = string_replace_all(text, "world", "RustLang");
assert_eq!(result, "Hello RustLang! This is Rust.");use string_replace_all::string_replace_all;
let text = "A B C D";
let result = string_replace_all(text, "B", "X");
assert_eq!(result, "A X C D"); // Spaces are properly collapseduse string_replace_all::string_replace_all;
let text = "Some special characters like * & % !";
let result = string_replace_all(text, "*", "[STAR]");
assert_eq!(result, "Some special characters like [STAR] & % !");use regex::Regex;
use string_replace_all::string_replace_all;
let text = "I think Ruth's dog is cuter than your dog!";
let regex = Regex::new("(?i)Dog").unwrap(); // Case-insensitive regex
let result = string_replace_all(text, ®ex, "ferret");
assert_eq!(result, "I think Ruth's ferret is cuter than your ferret!");