最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Match number with no decimal and greater than 10,000 - Stack Overflow

programmeradmin4浏览0评论

I am not very familiar with regex and am trying to create a regex code in JavaScript to match a string with only

  • whole numbers
  • no decimals/dots
  • and should be greater than 10,000

So far I have it like the ff. I think I am missing something as it still read through decimal numbers and == 10,000. How do I do that?

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

I am not very familiar with regex and am trying to create a regex code in JavaScript to match a string with only

  • whole numbers
  • no decimals/dots
  • and should be greater than 10,000

So far I have it like the ff. I think I am missing something as it still read through decimal numbers and == 10,000. How do I do that?

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

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

Share Improve this question asked Jun 18, 2019 at 9:25 dresdaindresdain 1748 bronze badges 3
  • 8 Why use RexExp at all? It seems like a wrong choice here. JS has number-parsing licked already. Why not just parseFloat(theString) or Number(theString) the entire string? It will fail/return NaN if it doesn't conform. You can then test it to ensure that it's an integral value less than 10000. – spender Commented Jun 18, 2019 at 9:30
  • Can't you use anything other than regex? maybe parse to int then do some checks? – Ammar Commented Jun 18, 2019 at 9:33
  • Thanks for you insight everyone! The bank I work with uses a particular form made by their in-house cms that strictly uses regex to check the inputs. That's why I'm limited to resort with regex – dresdain Commented Jun 18, 2019 at 9:58
Add a ment  | 

2 Answers 2

Reset to default 7

At the risk of not directly answering the question, JavaScript can already parse numbers. Why bother trying to reimplement this? Especially with RegExp?

Why not just parseFloat(theString) or Number(theString) the entire string?

It will fail/return NaN if what you have isn't a number, and you can test for this with 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

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$)[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 (i.e. after start of string (^), there is 10000 and then end of string position follows ($))
  • [1-9] - a digit from 1 to 9
  • [0-9]{4,} - any four or more digits
  • $ - end of string.
发布评论

评论列表(0)

  1. 暂无评论