带或不带逗号的整数的正则表达式
Regular expression for integer with or without commas
我想为各种数字创建正则表达式,即带或不带逗号的整数(+ve 和 -ve)和小数(+ve 和 -ve)。
例如,正则表达式应涵盖以下数字格式。
111 1.11 1,111 1,111.01 1,111,111.01
+111 +1.11 +1,111 +1,111.01 +1,111,111.01
-111 -1.11 -1,111 -1,111.01 -1,111,111.01
我已经创建了两个正则表达式来处理我的场景。
"^(\+|-)?[0-9]\d*(\.\d+)?$" // handles whole numbers with decimals
"^(\+|-)?[0-9]\d*(\,\d+)*?$" // handles whole numbers with commas
现在,我想合并这两个正则表达式以满足我的要求。
谁能帮帮我?
提前致谢。
这个怎么样:
^[+-]?\d+(,\d+)?(\.\d+)?$
您可以看到它正在运行 here。
您可以像这样合并这 2 个模式
^[+-]?[0-9]+(?:,[0-9]+)*(?:[.][0-9]+)?$
详情:
^
- 字符串的开头
[+-]?
- 可选的 +
或 -
[0-9]+
- 1 个或多个数字
(?:,[0-9]+)*
- 零个或多个序列:
,
- 逗号
[0-9]+
- 1 个或多个数字
(?:[.][0-9]+)?
- 一个可选的序列:
[.]
- 一个点
[0-9]+
- 1+ 位数
$
- 字符串结尾
一个更严格的正则表达式,只允许分组中的 3 位数字看起来像
^[+-]?[0-9]{1,3}(?:,[0-9]{3})*(?:[.][0-9]+)?$
^^^^^ ^^^
如果您还想匹配没有千位分隔符的整个部分:
^[+-]?(?:[0-9]{1,3}(?:,[0-9]{3})*|[0-9]+)(?:[.][0-9]+)?$
这是我的解决方案,逗号之间只允许 3 位数字:
^[+-]?\d{1,3}(?:,\d{3}|\d+)*(?:\.\d+)?$
解释:
^ : start of string
[+-]? : optional + or -
\d{1,3} : 1 to 3 digits (before the first optional comma)
(?: : non capturing group
,\d{3} : a comma followed by 3 digit
| : OR
\d+ : 1 or more digits
)* : group present 0 or more times
(?: : non capturing group
\.\d+ : decimal dot followed by 1 or more digits
)? : optional
$ : end of string
我想为各种数字创建正则表达式,即带或不带逗号的整数(+ve 和 -ve)和小数(+ve 和 -ve)。
例如,正则表达式应涵盖以下数字格式。
111 1.11 1,111 1,111.01 1,111,111.01
+111 +1.11 +1,111 +1,111.01 +1,111,111.01
-111 -1.11 -1,111 -1,111.01 -1,111,111.01
我已经创建了两个正则表达式来处理我的场景。
"^(\+|-)?[0-9]\d*(\.\d+)?$" // handles whole numbers with decimals
"^(\+|-)?[0-9]\d*(\,\d+)*?$" // handles whole numbers with commas
现在,我想合并这两个正则表达式以满足我的要求。
谁能帮帮我?
提前致谢。
这个怎么样:
^[+-]?\d+(,\d+)?(\.\d+)?$
您可以看到它正在运行 here。
您可以像这样合并这 2 个模式
^[+-]?[0-9]+(?:,[0-9]+)*(?:[.][0-9]+)?$
详情:
^
- 字符串的开头[+-]?
- 可选的+
或-
[0-9]+
- 1 个或多个数字(?:,[0-9]+)*
- 零个或多个序列:,
- 逗号[0-9]+
- 1 个或多个数字
(?:[.][0-9]+)?
- 一个可选的序列:[.]
- 一个点[0-9]+
- 1+ 位数
$
- 字符串结尾
一个更严格的正则表达式,只允许分组中的 3 位数字看起来像
^[+-]?[0-9]{1,3}(?:,[0-9]{3})*(?:[.][0-9]+)?$
^^^^^ ^^^
如果您还想匹配没有千位分隔符的整个部分:
^[+-]?(?:[0-9]{1,3}(?:,[0-9]{3})*|[0-9]+)(?:[.][0-9]+)?$
这是我的解决方案,逗号之间只允许 3 位数字:
^[+-]?\d{1,3}(?:,\d{3}|\d+)*(?:\.\d+)?$
解释:
^ : start of string
[+-]? : optional + or -
\d{1,3} : 1 to 3 digits (before the first optional comma)
(?: : non capturing group
,\d{3} : a comma followed by 3 digit
| : OR
\d+ : 1 or more digits
)* : group present 0 or more times
(?: : non capturing group
\.\d+ : decimal dot followed by 1 or more digits
)? : optional
$ : end of string