🎓 A1Learner
🔍

Rust Regex Replace and Split

Regex replace rewrites the text a pattern matches, and regex split cuts text at every match.

replace changes the first match

Only the first digit is touched. The rest of the text is left alone.

let re = Regex::new(r"\d").unwrap();
println!("{}", re.replace("a1 b2 c3", "X"));

replace_all changes every match

Same pattern. Same replacement. Every match is rewritten.

let re = Regex::new(r"\d").unwrap();
println!("{}", re.replace_all("a1 b2 c3", "X"));

Groups move into the replacement

The date groups trade places. Year, month, and day come back in a new order.

let re = Regex::new(r"(\d{4})-(\d{2})-(\d{2})").unwrap();
println!("{}", re.replace("2026-10-22", "$3/$2/$1"));

Named groups in the replacement

Names work in replacements too. The $ reads the group with that name.

let re = Regex::new(r"(?P<user>\w+)@(?P<host>\w+)").unwrap();
println!("{}", re.replace("ferris@example", "$user at $host"));

split cuts at every match

The pattern names the cut points. The pieces between them come back in order.

let re = Regex::new(r"[,;]").unwrap();
let parts: Vec<&str> = re.split("a,b;c,d").collect();
println!("{:?}", parts);

A real dollar sign needs $$

One $ is an instruction. Two of them print one real sign.

let re = Regex::new(r"(\d+)").unwrap();
println!("{}", re.replace_all("5 and 10", "$$$1"));

Example

// Cargo.toml: regex = "1"
use regex::Regex;

fn main() {
    let dates = Regex::new(r"(\d{4})-(\d{2})-(\d{2})").unwrap();
    let text = "Meet on 2026-10-22, pay on 2026-11-01.";
    println!("{}", dates.replace_all(text, "$3/$2/$1"));
    let spaces = Regex::new(r"\s+").unwrap();
    println!("[{}]", spaces.replace_all("too   many    spaces", " "));
}

Key points

  • Use replace to change the first match only, and replace_all to change every match
  • Both tools start from the same matches: replace rewrites them, and split cuts at them.
  • In the replacement text, $1 stands for group 1 and $name stands for the named group
  • Write ${1} when a letter or digit follows the group: the braces show where the group name ends
  • Use split to cut the text at every match and hand back the pieces between the matches
  • replace returns a Cow: the original text borrowed when nothing matched, a fresh String when it replaced something

In this example, two rewrites clean one text each. The date pattern captures year, month, and day. replace_all swaps every date into day, month, year order. Two dates change in one call. Then the \s+ pattern matches each run of spaces. One space replaces each run, however wide it was.

Note

The $ sign is special inside a replacement: write $$ to place one real dollar sign in the result.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Rust Playground

Exercise

What is the difference between replace and replace_all?