Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Less greedy named capture groups #690

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
21 changes: 15 additions & 6 deletions src/expand.rs
Original file line number Diff line number Diff line change
Expand Up @@ -128,19 +128,25 @@ impl From<usize> for Ref<'static> {
fn find_cap_ref<T: ?Sized + AsRef<[u8]>>(
replacement: &T,
) -> Option<CaptureRef> {
let mut i = 0;
let rep: &[u8] = replacement.as_ref();
if rep.len() <= 1 || rep[0] != b'$' {
return None;
}
let mut brace = false;
i += 1;
let mut numeric = false;
let mut i = 1;

if rep[i] == b'{' {
brace = true;
i += 1;
}
} else if is_cap_number(&rep[i]) {
numeric = true;
};

let is_allowed = if numeric { is_cap_number } else { is_valid_cap_letter };
let mut cap_end = i;
while rep.get(cap_end).map_or(false, is_valid_cap_letter) {

while rep.get(cap_end).map_or(false, is_allowed) {
cap_end += 1;
}
if cap_end == i {
Expand Down Expand Up @@ -173,6 +179,9 @@ fn is_valid_cap_letter(b: &u8) -> bool {
_ => false,
}
}
fn is_cap_number(b: &u8) -> bool {
matches!(*b, b'0'..=b'9')
}

#[cfg(test)]
mod tests {
Expand Down Expand Up @@ -205,7 +214,7 @@ mod tests {
find!(find_cap_ref4, "$5", c!(5, 2));
find!(find_cap_ref5, "$10", c!(10, 3));
// see https://github.com/rust-lang/regex/pull/585 for more on characters following numbers
find!(find_cap_ref6, "$42a", c!("42a", 4));
find!(find_cap_ref6, "$42a", c!(42, 3));
find!(find_cap_ref7, "${42}a", c!(42, 5));
find!(find_cap_ref8, "${42");
find!(find_cap_ref9, "${42 ");
Expand All @@ -214,7 +223,7 @@ mod tests {
find!(find_cap_ref12, " ");
find!(find_cap_ref13, "");
find!(find_cap_ref14, "$1-$2", c!(1, 2));
find!(find_cap_ref15, "$1_$2", c!("1_", 3));
find!(find_cap_ref15, "$1_$2", c!(1, 2));
find!(find_cap_ref16, "$x-$y", c!("x", 2));
find!(find_cap_ref17, "$x_$y", c!("x_", 3));
}
2 changes: 1 addition & 1 deletion tests/replace.rs
Original file line number Diff line number Diff line change
Expand Up @@ -128,5 +128,5 @@ replace!(
r"(.)",
"b",
t!("${1}a $1a"),
"ba "
"ba ba"
);