Skip to content

Regex parse error when try to match string literals "{{xxx}}" #632

@bofeng

Description

@bofeng

My code in Python works like this:

>>> content = "{{ static_prefix }}/home/js/asdf.js";
>>> a = re.compile("{{\\s*static_prefix\\s*}}");
>>> a.sub("/static", content)
'/static/home/js/asdf.js'

If I code the same logic with regex crate,

use regex::Regex;

fn main() {
    let content = "{{ static_prefix }}/home/js/asdf.js";
    let reg = Regex::new("{{\\s*static_prefix\\s*}}").unwrap();
    println!("{}", reg.replace(content, "/static"));
}

I got error:

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
regex parse error:
    {{\s*static_prefix\s*}}
    ^
error: repetition operator missing expression

But if I escape {{ with backslash, it works:

use regex::Regex;

fn main() {
    let content = "{{ static_prefix }}/home/js/asdf.js";
    let reg = Regex::new("\\{\\{\\s*static_prefix\\s*\\}\\}").unwrap();
    println!("{}", reg.replace(content, "/static"));
}

I tried in Python and Go, to match this string, I don't need to escape {{ and }}, but with this regex crate in Rust, I need to put the extra escape, otherwise I got the above "parse error", regex can't compile.

Is this a bug?

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions