简体   繁体   English

正则表达式匹配数字的科学记数法但不匹配其他字母

[英]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 位的正数值以及数字的科学记数法吗?

You copied the exact regex from the other answer which asked for more requirements ie matching equation.您从另一个答案中复制了确切的正则表达式,该答案要求更多要求,即匹配方程。 Removing those with a bit modification you could try:删除那些稍加修改的内容,您可以尝试:

^[+-]?\d+(?:\.\d*(?:[eE][+-]?\d+)?)?$

Live demo现场演示

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:注意事项:

  • no leading zeros allowed不允许前导零
  • no .没有. without decimal places allowed (can be fixed by using \\.\\d{0,2} )不允许小数位(可以使用\\.\\d{0,2}修复)
  • more decimal places are possible due to the e-notation (eg 1e-3)由于 e-notation(例如 1e-3),更多的小数位是可能的
  • i-Modifier should be used应该使用 i-Modifier
  • you might just want to use your languages ability to parse and compare float values您可能只想使用您的语言能力来解析和比较浮点值

Demo: https://regex101.com/r/ljOaIb/1/演示: https : //regex101.com/r/ljOaIb/1/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM