Home > OS >  Replace everything between 2 characters exclusive with Rust Regex
Replace everything between 2 characters exclusive with Rust Regex

Time:10-15

I want to replace the 6379 in the string "172.20.0.3:6379@16379" with another port number.

I've tried this but it says the escape sequence "\K" is not valid.

use regex::Regex;
let ip = "172.20.0.3:6379@16379"
let re = Regex::new(r":\K[^@] ").unwrap();
let new_ip = re.replace(ip, "1234");

CodePudding user response:

You can use :[^:@] @ to match everything between : and @ inclusively, and add the two characters back in the replacement.

let re = Regex::new(r":[^:@] @").unwrap();
let new_ip = re.replace(ip, ":1234@");

Rust playground

  • Related