Skip to content

Improper Regex::replace behaviour #291

Closed
@ConnorGray

Description

@ConnorGray

The regular express ((IMG|CAM|MG|MB2)_|(DSCN|CIMG))(?P<n>[0-9]+)$ is a match on the text "CIMG2341" but expected result of regex.replace("CIMG2341", "$n") returns "2341" is not found, instead "CIMG2341" is returned. The correct behavior is observer when the original regex is replaced with ((MG|MB2)_|(DSCN|CIMG))(?P<n>[0-9]+)$.

extern crate regex;

use regex::{Regex};

fn main() {
    let text = "CIMG2341";

    let regex = Regex::new(
        "((IMG|CAM|MG|MB2)_|(DSCN|CIMG))(?P<n>[0-9]+)$").unwrap();

    assert!(regex.is_match(text)); // This works (no panic)

    let renamed = regex.replace(text, "$n");
    assert_eq!(renamed, "2341"); // This panics
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions