1

I have been trying to make the regex of 16 bit signed integer(-32768 to 32767) taking reference from this link of 32 bit integer.

Till now, I tried this:

^-?([0-9]{1,5}|32[0-6]{3}|32[0-6]{2}|327[0-5][0-8])$|^(-32768)$

But, its not matching well.

Please guide.

HitomiTenshi
  • 514
  • 2
  • 6
  • 20
Shachi
  • 1,858
  • 3
  • 23
  • 41
  • 8
    Why not just do it numerically? It's not really a job for regular expressions. – Pointy Jun 20 '19 at 12:28
  • 2
    Just use `if (intUs >= -32768 && intUs <= 32767)` ... save yourself the headache of a cryptic regex which would be hard to interpret and maintain. – Tim Biegeleisen Jun 20 '19 at 12:30
  • I agree with @Pointy. You *could* do this via regex but it isn't a very good idea. I assume this is for some sort of validation - isn't it possible to have a custom validator there? – VLAZ Jun 20 '19 at 12:31
  • I understand the complexity of regex though, I just want a uniform code as there are many other regex used.. which are relatively simpler... For using if() i will have to change a lot of code. – Shachi Jun 20 '19 at 12:53
  • 2
    It's short *signed* integer. – revo Jun 20 '19 at 13:24

1 Answers1

2

Try (however using regexp is not good idea - if is better)

let r=/^(-?(\d{1,4}|[012]\d{4}|3[01]\d{3}|32[0123456]\d{2}|327[012345]\d{1}|3276[01234567])|-32768)$/;

// test
console.log("-32768", r.test("-32768")) ;
console.log(" -9876", r.test("-9876")) ;
console.log("  9876", r.test("9876")) ;
console.log(" 32767", r.test("32767")) ;
console.log("-32769", r.test("-32769")) ;
console.log(" 32768", r.test("32768")) ;
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345