-2

I need to check if the first 6 digits of a number are from 222100-272099. This is in JavaScript, and I'm not sure how to go about implementing it. My initial thought was something like: match(/^2[2-7][0-9]$/), but I'm not sure how to specify this range correctly.

  • (/^2[2-7][0-9]{4}$/) might be what you are looking for? {number} is how many of the previous character you want. If that does the trick I'll write up an answer. – sniperd Jul 24 '17 at 13:51
  • Welcome to Stack Overflow. Please read first in the help center, how to ask a good question on this forum: https://stackoverflow.com/help/how-to-ask. So we can better unterstand your question and can help you with your problems. – Julian Schmuckli Jul 24 '17 at 13:51
  • 1
    [Now you have two problems](https://blog.codinghorror.com/regular-expressions-now-you-have-two-problems/). – Phylogenesis Jul 24 '17 at 13:53
  • @sniperd Your regex would also match 279000, which is not in the range.. but that's just not a job for regexs. – idmean Jul 24 '17 at 13:53
  • Oh, right! Ha. I should probably read the whole question :) – sniperd Jul 24 '17 at 13:56

2 Answers2

3

You shouldn’t really use a RegEx for that. It is better to substring the string and then compare:

const n = Number.parseInt(str.substr(0, 6), 10);
if (222100 <= n && n <= 272099) {
   // ...
idmean
  • 14,540
  • 9
  • 54
  • 83
0

Regular expressions are for pattern matching in strings: Wikipedia: Regular expression

You can use JavaScript's parseInt() function to turn your 6 numeric character string into a number that can be used to do a simple greater than/less than check. W3C: parseInt()

Brian
  • 41
  • 1
  • 8