How to Check If A String Is a Number (Numeric) using Regex (C++/

  • 时间:2020-09-18 17:26:09
  • 分类:网络文摘
  • 阅读:137 次

Validate if a given string can be interpreted as a decimal number.

Some examples:
“0” => true
” 0.1 ” => true
“abc” => false
“1 a” => false
“2e10″ => true
” -90e3 ” => true
” 1e” => false
“e3″ => false
” 6e-1″ => true
” 99e2.5 ” => false
“53.5e93″ => true
” –6 ” => false
“-+3” => false
“95a54e53” => false

Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one. However, here is a list of characters that can be in a valid decimal number:

Numbers 0-9
Exponent – “e”
Positive/negative sign – “+”/”-”
Decimal point – “.”
Of course, the context of these characters also matters in the input.

In Javascript, you can convert a string to number using the Number constructor – which returns a NaN if it is not a valid number. Thus, the following Javascript code tests if a number is numeric:

1
2
3
4
5
6
7
8
9
/**
 * @param {string} s
 * @return {boolean}
 */
var isNumber = function(s) {
    s = s.trim();
    if (!s) return false;
    return !isNaN(Number(s));
};
/**
 * @param {string} s
 * @return {boolean}
 */
var isNumber = function(s) {
    s = s.trim();
    if (!s) return false;
    return !isNaN(Number(s));
};

The empty string or the whitespace-only strings will be converted to zeros, thus, those white-space values need to be exclusively checked.

1
2
Number("") // 0
Number("    ") // 0
Number("") // 0
Number("    ") // 0

Regular Expression to Validate a Number String

The regex pattern is: ^\s*[-+]?((\d+(\.\d+)?)|(\d+\.)|(\.\d+))(e[-+]?\d+)?\s*$ Thus, in Javascript to test a string against a regex pattern:

1
2
3
4
5
6
7
/**
 * @param {string} s
 * @return {boolean}
 */
var isNumber = function(s) {
    return /^\s*[-+]?((\d+(\.\d+)?)|(\d+\.)|(\.\d+))(e[-+]?\d+)?\s*$/.test(s);
};
/**
 * @param {string} s
 * @return {boolean}
 */
var isNumber = function(s) {
    return /^\s*[-+]?((\d+(\.\d+)?)|(\d+\.)|(\.\d+))(e[-+]?\d+)?\s*$/.test(s);
};

Or in C++:

1
2
3
4
5
6
7
8
9
#include <regex>
regex r(R"(^^\s*[-+]?((\d+(\.\d+)?)|(\d+\.)|(\.\d+))(e[-+]?\d+)?\s*$)");
 
class Solution {
public:
    bool isNumber(const string& s) {
        return regex_match(s, r);
    }
};
#include <regex>
regex r(R"(^^\s*[-+]?((\d+(\.\d+)?)|(\d+\.)|(\.\d+))(e[-+]?\d+)?\s*$)");

class Solution {
public:
    bool isNumber(const string& s) {
        return regex_match(s, r);
    }
};

Please note the regex library needs to be included in order to use the regex_match function in C++.

–EOF (The Ultimate Computing & Technology Blog) —

推荐阅读:
数学题:利用图中的阴影部分刚好可以做成一个圆柱形油桶  数学题:水面高度正好是圆锥高度的一半  数学题:把高是10cm的圆柱按下图切开,分成17份  数学题:一批同学画画,2人合用一瓶红颜料  数学题:再加多少毫升牛奶,才可以把杯子装满?  把圆柱削成一个最大的圆锥求削去部分体积  用一张半径为15厘米的半圆形纸片围成一个圆锥  归期将近,珍惜相遇  美丽的峨眉山作文  人生路上,未雨绸缪作文 
评论列表
添加评论