joo
joo

Reputation: 13

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"));
}

Upvotes: 1

Views: 63

Answers (1)

t.niese
t.niese

Reputation: 40872

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

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

Upvotes: 1

Related Questions