Is this the correct way to use regex.replace? #911
-
I'm trying to write in Rust this OS answer for javascript. PLAYGROUND here: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=bb24fc62bc74fa7b3103f238b4660455 pub fn magic(input: &str) -> String {
let reg = regex::Regex::new(r"^[ \t]+|[ \t]+$|([ \t]){2,}/mg").unwrap();
reg.replace(input, "$1").to_string()
}
#[cfg(test)]
fn magic_data() -> std::collections::HashMap<&'static str, &'static str> {
std::collections::HashMap::from([
(" ", ""),
(" a l l lower ", "a l l lower"),
(
" i need\n new lines\n\n many times ",
"i need\nnew lines\n\nmany times",
),
(
" i need \n new lines \n\n many times ",
"i need\nnew lines\n\nmany times",
),
(
" i need \r\n new lines\r\nmany times ",
"i need\nnew lines\nmany times",
),
(
" i need \t new lines\t \t many times ",
"i need new lines many times",
),
(" à la ", "à la"),
])
}
#[test]
fn test() {
for (k, v) in magic_data() {
assert_eq!(magic(k), v)
}
} But as you can see all the tests fail! Why? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Here's the first problem that pops out at me:
Why are you adding
This is your second problem. From the docs of
It only replaces the first match. It looks like you want all matches replaced. So you should switch to Your third problem is that
But the corresponding SO answer has this:
Fixing the CRLF issue in the regex is a little tricky, but it can be done:
Given all of that, your tests pass: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=8e63bdc73c1c0fa2f6412c78a119f962 |
Beta Was this translation helpful? Give feedback.
Here's the first problem that pops out at me:
Why are you adding
/mg
to the regex? That only works for Javascript regex literals. This is Rust. Rust does not have regex literals. The docs have several examples for how to set flags. In this case, you'd want(?m)^[ \t]+|[ \t]+$|([ \t]){2,}
. Theg
flag is irrelevant in Rust, and only exists in Javascript because of some oddities with its regex API.This is your second problem. From the docs of
Regex::replace
:It only replaces the first match. It looks like you want all matches replaced. So you should s…