Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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+))

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading