双精度正则表达式

问题描述 投票:0回答:7

我有这个正则表达式

"^[0-9]+\.?[0-9]*$")
来匹配 Visual C++ 中的双精度数或整数,但它似乎不起作用。有任何想法吗?

这就是我应用代码的方式:

if (System::Text::RegularExpressions::Regex::IsMatch(e0, "^[0-9]+\.?[0-9]*$")){
     e0_val = System::Convert::ToDouble(e0);
}
regex c++-cli
7个回答
22
投票

上面的正则表达式并不完美,因为它接受“09”,这不是一个有效的数字。更好的表达方式是:

"^(-?)(0|([1-9][0-9]*))(\\.[0-9]+)?$"

地点:

1. is an optional negative sign;
2. is zero or a valid non-zero integer;
4. is the optional fracture part;

理论上,断裂部分应该写成“(\.[0-9]*[1-9])?” 相反,因为数字不能有尾随零。实际上,源字符串可能是用固定位数创建的,例如:

printf("%.1f", x);

因此它可能很容易以零字符结尾。当然,这些都是定点表示,而不是双打本身。双数可以 也可以写成 -1.23e-4 而不是 -0.000123。


20
投票

正则表达式本身没有任何问题,问题在于你的转义。您需要对

\
字符进行双重转义,因为它也是 C++ 字符串转义字符。

此外,还有一种边缘情况,该正则表达式会认为

1.
是有效的浮点指针数字。因此,使用
/^[0-9]+(\\.[0-9]+)?$
可能会更好,这消除了这种可能性。


5
投票

也许不是直接答案,只是有用的信息。正则表达式:

std::regex rx(R"(^([+-]?(?:[[:d:]]+\.?|[[:d:]]*\.[[:d:]]+))(?:[Ee][+-]?[[:d:]]+)?$)");

匹配字符串:

"1", "0", "10",
"1000.1", "+1",
"+10", "-10", "1.",
".1", "1.1", "+1.",
"-1.", "+.1", "-.1",
"009", "+009", "-009",
"-01e0", "+01E0", "+1e-1",
"+1e+1", "+1.e1", "1E1",
"1E+1", "0.001e-12", "0.111111111111111"

并且不匹配接下来的字符串:

".", "1a", "++1",
"+-1", "+", "-.",
"-", "--1.", "1.e.1",
"1e.1", "0+.e0"

第一个看起来像 C++ 中

double
类型的有效值,例如
double test = +009.e+10
还可以。

在 ideone.com 中播放:https://ideone.com/ooF8sG


4
投票

/^[0-9]+.[0-9]+$:用于双打。

接受 123.123 种类型。


3
投票
/^[0-9]*[.]?[0-9]+$/

上面的正则表达式适用于双精度数,例如“45.5”、“12”、“.12”


0
投票
(\d+)?\.(\d+)?

上面的正则表达式适用于双打,例如 "45.5""12."".12"


0
投票
    constexpr char double_regex_s[53] =
        "^" // accept only if it matches the beginning of the string
        "(-?)" // accept a single optional negation
        "(0|([1-9][0-9]*))" // number is either zero or some integer that does not start with zero
        "(" // begin optional decimals
            "\\." // require a dot
            "[0-9]+" // any digit is fine, but at least one (std::atof does not require but chrome requires digits after dot)
        ")?" // end optional decimals
        "(" // begin optional scientific exponent
            "[eE]" // require an e or E
            "[-+]?" // accept optional plus or minus
            "[0-9]+" // any digit is fine (tested in chrome JSON.parse(1E000003) works)
        ")?" // end optional scientific exponent
        "$" // accept only if it matches up to the end of the string
        ;
© www.soinside.com 2019 - 2024. All rights reserved.