简体   繁体   English

匹配号码,无小数,大于10,000

[英]Match number with no decimal and greater than 10,000

I am not very familiar with regex and am trying to create a regex code in JavaScript to match a string with only 我对正则表达式并不是很熟悉,并且我试图在JavaScript中创建一个正则表达式代码以仅匹配字符串

  • whole numbers 整数
  • no decimals/dots 没有小数点/点
  • and should be greater than 10,000 并且应该大于10,000

So far I have it like the ff. 到目前为止,我有它像ff。 I think I am missing something as it still read through decimal numbers and == 10,000. 我想我错过了一些东西,因为它仍然读取十进制数字和== 10,000。 How do I do that? 我怎么做?

[1-9](?!\\.)\\d[0-9]{3,}

https://regex101.com/r/hG2iU7/61 https://regex101.com/r/hG2iU7/61

At the risk of not directly answering the question, JavaScript can already parse numbers. 如果没有直接回答问题,JavaScript可以解析数字。 Why bother trying to reimplement this? 为什么要重新尝试重新实现呢? Especially with RegExp? 特别是使用RegExp?

Why not just parseFloat(theString) or Number(theString) the entire string? 为什么不只是parseFloat(theString)Number(theString)整个字符串?

It will fail/return NaN if what you have isn't a number, and you can test for this with isNaN . 如果您拥有的不是数字,它将失败/返回NaN ,您可以使用isNaN对此进行测试。

If it doesn't fail, you can then test it to ensure that it's an integral value: 如果它没有失败,你可以测试它以确保它是一个整数值:

const isIntegral = Math.trunc(theNumber) === theNumber;

and is less than 10000 并且小于10000

const isLessThan10000 = theNumber < 10000;

This code is going to be much easier to read and maintain than a regular expression. 与正则表达式相比,此代码易于阅读和维护。

You may use 你可以用

^[1-9][0-9]{4,}$

To exclude 10000 add a (?!10000$) lookahead: 要排除10000添加一个(?!10000$)前瞻:

^(?!10000$)[1-9][0-9]{4,}$
 ^^^^^^^^^^

See the regex demo and the regex graph : 请参阅正则表达式演示正则表达式图

在此输入图像描述

Details 细节

  • ^ - start of string ^ - 字符串的开头
  • (?!10000$) - a negative lookahead that cancels the match if the whole string is equal to 10000 (ie after start of string ( ^ ), there is 10000 and then end of string position follows ( $ )) (?!10000$) - 如果整个字符串等于10000 ,则取消匹配的负前瞻(即在字符串( ^ )开始后,有10000 ,然后字符串位置结束后跟( $ ))
  • [1-9] - a digit from 1 to 9 [1-9] - 19的数字
  • [0-9]{4,} - any four or more digits [0-9]{4,} - 任何四位或更多位数
  • $ - end of string. $ - 结束字符串。

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

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