Skip to content

RUST-2399 Add function to escape a string for use in a Regex #655

@tyilo

Description

@tyilo

We do a lot of queries for fields having a specific prefix. The only way(?) to do this in MongoDB is using a regex. To do this for an arbitrary input string it needs to be escaped.

Possible alternative is to use regex-syntax/regex-lite's escape function. These don't escape the NUL byte which is needed for bson::Regex's CString pattern. Furthermore the regex syntax in these are not the same as PCRE2 that is used by MongoDB, so there is no guarantee that escape will always work.

Proposed solution:

// Either a free-standing function:
pub fn regex_escape(s: &str) -> CString;

// or a function on `bson::Regex`:
impl Regex {
    pub fn escape(s: &str) -> CString;
}

To actually achieve the prefix match easily it should also be possible to concatenate two CString:

fn prefix_regex(s: &str) -> bson::Regex {
    let mut pattern = CString::from(cstr!("^"));
    pattern += regex_escape(s);
    bson::Regex {
        pattern,
        options: CString::new(),
    }
}

Metadata

Metadata

Assignees

Labels

tracked-in-jiraTicket filed in Mongo's Jira system

Type

No type
No fields configured for issues without a type.

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions