意外的正则表达式模式匹配

huangapple go评论60阅读模式
英文:

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

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

答案1

得分: 1

^(\d+\.?\d*)|^(\.\d+) 或者添加另一个组:^((\d+\.?\d*)|(\.\d+))

英文:

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

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

huangapple
  • 本文由 发表于 2023年2月14日 03:05:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/75440210.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定