Search code examples
regexrustregex-group

Unexpected regex pattern matching


I'd like to match only for python-like floats, that is for example: 0.1, .1 or 0.. I wrote this regex: r"(\d+\.?\d*)|(\.\d+)" and found out that it also matches with "(.6", which I haven't intended. My guess is it has something to do with grouping with parenthesis, but I haven't escaped any parenthesis with a backslash.

I'm using version 1.7.1 of regex crate and cargo 1.67.0.

use regex::Regex;
fn main() {
    let pattern = Regex::new(r"^(\d+\.?\d*)|(\.\d+)").unwrap();
    assert!(pattern.is_match("(.6"));
}

Solution

  • The regex ^(\d+\.?\d*)|(\.\d+) matches ^(\d+\.?\d*) or (\.\d+).

    You want to have ^(\d+\.?\d*)|^(\.\d+) or add another group. ^((\d+\.?\d*)|(\.\d+))