Regular Expression to accept all the number with decimal from 0 to 168 followed by N or S

Viewed 98

I have to build a regular exp which will accept all the numbers from 0 to 168 followed by "N" or "S".

I have prepared the following regular exp which is working fine except that it considers 168.11 as valid input.

Regular Exp:

/\b([1-9]|[1-9][0-9]|1[01][0-9]|16[0-8])(\.\d{1,2})?[N,S]?$/

Valid:

168S
11.2
 10
140
125N
130S
3S
3.2
168.00S

Invalid:

168.11
168.12S
168.12N

Can anyone suggest what I am missing? Thank you!

3 Answers

You may use this regex with optional matches:

^\s*(?:(?:\d|[1-9]\d|1[0-5]\d|16[0-7])(?:\.\d{1,2})?|168(?:\.0{1,2})?)[NS]?$

RegEx Demo

RegEx Details:

  • ^\s*: Match 0 or more horizontal spaces at start
  • (?:: Start non-capture group #1
    • (?:: Start non-capture group #2
      • \d: A single digit to numbers from 0 to 9
      • |: OR
      • [1-9]\d: Match numbers from 10 to 99
      • |: OR
      • 1[0-5]\d: Match numbers from 100 to 159
      • |: OR
      • 16[0-7]: Match numbers from 160 to 167
    • ): End non-capture group #2
    • (?:\.\d{1,2})?: Match optional decimal point followed by 1 or 2 digits
    • |: OR
    • 168: Match 168
    • (?:\.0{1,2})?: Match optional .0 or .00
  • ): End non-capture group #1
  • [NS]?: Match optional N or S before end
  • $: End

What about:

^ *(?!0|168\.0?[1-9]|169)(?:\d?\d|1[0-6]\d)(?:\.\d?\d)?[SN]?$

See an online demo

  • ^ - Start line anchor.
  • * - 0+ space characters.
  • (?!0|168\.0?[1-9]|169) - Negative lookahead for a leading zero or literally "168." followed by decimal number containing anything other than zero or literally "169".
  • (?: - Open non-capture group:
    • \d?\d - 1 Or 2 digits.
    • | - Or:
    • 1[0-6]\d - A literal "1" followed by numbers 00 upto 69.
    • ) - Close non-capture group.
  • (?:\.\d?\d)? - A 2nd non-capture group (optional) for a decimal number (1-2 digits).
  • [SN]? - Optionally match "S" or "N".
  • $ - End line anchor.

You can also use

^(?:(?:[0-9]|\d\d|1[0-5]\d|16[0-7])(?:\.\d\d+)?|168(?:\.0+))[NS]?$

with regexr demo

enter image description here

Related