[英]Regex to match scientific notation of numbers but not other letters
I want to write a regex to match all positive double numbers with maximum 2 digits after decimal point.我想编写一个正则表达式来匹配所有小数点后最多 2 位的正双数。
My first approach was this:我的第一种方法是这样的:
^\\d+(?:\\.\\d{1,2})?$
it works fine for most cases but not for scientific notations, for example 10000000
when it's written as 1.0E7
.它适用于大多数情况,但不适用于科学记数法,例如10000000
写为1.0E7
。
I've found an answer here and I made adapted it to my case resulting:我在这里找到了一个答案,并根据我的情况进行了调整,结果是:
[\\s=]+([+]?(?:0|[1-9]\\d*)(?:\\.\\d*)?(?:[eE][+\\-]?\\d{1,2}))$
but now it returns false for a lot of "good" values.但现在它为很多“好”值返回false。
Any idea how to make it match only positive numerical values with 0 to 2 digits after the decimal point but also the scientific notation of the numbers?知道如何使它只匹配小数点后 0 到 2 位的正数值以及数字的科学记数法吗?
Assuming zero is not a positive number, you can use假设零不是正数,您可以使用
^(?:0\.(?:0[1-9]|[1-9]\d?)|[1-9]\d*(?:\.\d{1,2})?)(?:e[+-]?\d+)?$
where在哪里
(?:0\\.(?:0[1-9]|[1-9]\\d?)
matches a positive number smaller than 1 with at most 2 decimal places (?:0\\.(?:0[1-9]|[1-9]\\d?)
匹配小于 1 且最多 2 个小数位的正数[1-9]\\d*(?:\\.\\d{1,2})?
matches a positive number equal or larger than 1, with optional up to 2 decimal places匹配一个等于或大于 1 的正数,可选择最多 2 个小数位(?:e[+-]?\\d+)?
optionally matches the scientific notation可选匹配科学记数法Caveats:注意事项:
.
没有.
without decimal places allowed (can be fixed by using \\.\\d{0,2}
)不允许小数位(可以使用\\.\\d{0,2}
修复)Demo: https://regex101.com/r/ljOaIb/1/演示: https : //regex101.com/r/ljOaIb/1/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.