mirror of
https://github.com/storytold/gridcraft.git
synced 2026-11-03 17:16:14 -06:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b0405ef9c3 |
@@ -308,6 +308,8 @@ mod tests {
|
||||
assert_eq!(ev("REGEXREPLACE", vec![t("2026-10-22"), t("(\\d+)-(\\d+)-(\\d+)"), t("$3/$2/$1")]), Value::text("22/10/2026"));
|
||||
assert_eq!(ev("REGEXREPLACE", vec![t("abc"), t("x*"), t("-")]), Value::text("-a-b-c-"));
|
||||
assert_eq!(ev("REGEXREPLACE", vec![t("a1b2"), t("[0-9]"), t("#"), n(2.0)]), Value::text("a1b#"));
|
||||
assert_eq!(ev("REGEXREPLACE", vec![t("a1b2"), t("[0-9]"), t("#"), n(-2.0)]), Value::text("a#b2"));
|
||||
assert_eq!(ev("REGEXREPLACE", vec![t("a1b2"), t("[0-9]"), t("#"), n(-3.0)]), Value::text("a1b2"));
|
||||
// One match whose replacement repeats it 10,000 times: refused before it is built.
|
||||
assert_eq!(ev("REGEXREPLACE", vec![t(&many), t("^.*$"), t(&"$0".repeat(10_000))]), Value::Error(CellError::Value));
|
||||
assert_eq!(ev("REGEXREPLACE", vec![t(&many), t("^.*$"), t(&"$0".repeat(10_000)), n(1.0)]), Value::Error(CellError::Value));
|
||||
|
||||
@@ -883,13 +883,24 @@ fn regexreplace(a: &[Arg], _c: &mut dyn Ctx) -> R<Value> {
|
||||
out.push_str(s.get(last..).unwrap_or_default());
|
||||
return check_len(out);
|
||||
}
|
||||
let caps: Vec<regex::Captures> = re.captures_iter(&s).collect();
|
||||
let k = occ.unsigned_abs() as usize;
|
||||
let idx = if occ > 0 { k.checked_sub(1) } else { caps.len().checked_sub(k) };
|
||||
let Some(cap) = idx.and_then(|i| caps.get(i)) else { return text_val(s) };
|
||||
// Keeps only the wanted match's captures: the nth from the front, or a window of the last `k`.
|
||||
let cap = if occ > 0 {
|
||||
re.captures_iter(&s).nth(k - 1)
|
||||
} else {
|
||||
let mut last = std::collections::VecDeque::new();
|
||||
for cap in re.captures_iter(&s) {
|
||||
if last.len() == k {
|
||||
last.pop_front();
|
||||
}
|
||||
last.push_back(cap);
|
||||
}
|
||||
if last.len() == k { last.pop_front() } else { None }
|
||||
};
|
||||
let Some(cap) = cap else { return text_val(s) };
|
||||
let Some(m) = cap.get(0) else { return text_val(s) };
|
||||
out.push_str(s.get(..m.start()).unwrap_or_default());
|
||||
expand_capped(cap, &rep, &mut out, limit).ok_or(CellError::Value)?;
|
||||
expand_capped(&cap, &rep, &mut out, limit).ok_or(CellError::Value)?;
|
||||
out.push_str(s.get(m.end()..).unwrap_or_default());
|
||||
check_len(out)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user