Skip to content

Commit e59f63b

Browse files
Lapin0tEthan Pailes
authored and
Ethan Pailes
committed
Fix Regex::replacen when replacing an empty match.
Fixes #393, #394.
1 parent 528fc02 commit e59f63b

File tree

3 files changed

+13
-8
lines changed

3 files changed

+13
-8
lines changed

src/re_bytes.rs

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -494,19 +494,20 @@ impl Regex {
494494
mut rep: R,
495495
) -> Cow<'t, [u8]> {
496496
if let Some(rep) = rep.no_expansion() {
497+
let mut it = self.find_iter(text).enumerate().peekable();
498+
if it.peek().is_none() {
499+
return Cow::Borrowed(text);
500+
}
497501
let mut new = Vec::with_capacity(text.len());
498502
let mut last_match = 0;
499-
for (i, m) in self.find_iter(text).enumerate() {
503+
for (i, m) in it {
500504
if limit > 0 && i >= limit {
501505
break
502506
}
503507
new.extend_from_slice(&text[last_match..m.start()]);
504508
new.extend_from_slice(&rep);
505509
last_match = m.end();
506510
}
507-
if last_match == 0 {
508-
return Cow::Borrowed(text);
509-
}
510511
new.extend_from_slice(&text[last_match..]);
511512
return Cow::Owned(new);
512513
}

src/re_unicode.rs

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -583,19 +583,20 @@ impl Regex {
583583
// replacements inside the replacement string. We just push it
584584
// at each match and be done with it.
585585
if let Some(rep) = rep.no_expansion() {
586+
let mut it = self.find_iter(text).enumerate().peekable();
587+
if it.peek().is_none() {
588+
return Cow::Borrowed(text);
589+
}
586590
let mut new = String::with_capacity(text.len());
587591
let mut last_match = 0;
588-
for (i, m) in self.find_iter(text).enumerate() {
592+
for (i, m) in it {
589593
if limit > 0 && i >= limit {
590594
break
591595
}
592596
new.push_str(&text[last_match..m.start()]);
593597
new.push_str(&rep);
594598
last_match = m.end();
595599
}
596-
if last_match == 0 {
597-
return Cow::Borrowed(text);
598-
}
599600
new.push_str(&text[last_match..]);
600601
return Cow::Owned(new);
601602
}

tests/replace.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,3 +36,6 @@ replace!(no_expand2, replace,
3636

3737
// See https://github.com/rust-lang/regex/issues/314
3838
replace!(match_at_start_replace_with_empty, replace_all, r"foo", "foobar", t!(""), "bar");
39+
40+
// See https://github.com/rust-lang/regex/issues/393
41+
replace!(single_empty_match, replace, r"^", "bar", t!("foo"), "foobar");

0 commit comments

Comments
 (0)