Skip to content

Instantly share code, notes, and snippets.

@awwsmm
Last active February 27, 2018 17:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save awwsmm/d7cb6ee18bb88e47f0a104b3286413e0 to your computer and use it in GitHub Desktop.
Save awwsmm/d7cb6ee18bb88e47f0a104b3286413e0 to your computer and use it in GitHub Desktop.

Regex to find numbers

The following regex finds hexadecimal, octal, and decimal numbers:

((?:[+-])?(?:(?:0?\.[0-9]*)|(?:[1-9]+\.?[0-9]*))(?:[eE][+-]?(?:(?:0?\.[0-9]*)|(?:[0-9]+\.?[0-9]*)))?)|(0x[0-9a-fA-F]+)|(0[0-9]*)

Escaped ("string safe"):

((?:[+-])?(?:(?:0?\\.[0-9]*)|(?:[1-9]+\\.?[0-9]*))(?:[eE][+-]?(?:(?:0?\\.[0-9]*)|(?:[0-9]+\\.?[0-9]*)))?)|(0x[0-9a-fA-F]+)|(0[0-9]*)

Expanded...

(                          #  decimal:
  (?:[+-])?                #    optional sign +/-
  (?:                      #    followed by a "numerical part", in one of two formats:
    (?:0?\.[0-9]*)         #      (1): 0., 0.3, .04, 0.005, 0.0
    |                      #
    (?:[1-9]+\.?[0-9]*)    #      (2): 1.0, 900, 3
  )                        #
  (?:                      #    optional exponential notation
    [eE][+-]?              #      one of: E+, E-, e+, e-, e, E
    (?:                    #        followed by
      (?:0?\.[0-9]*)       #          same as above (1)
      |                    #            OR
      (?:[0-9]+\.?[0-9]*)  #          same as above (2)
    )                      #
  )?                       #    (exponential notation is optional)
)                          #
|                          #    OR
(0x[0-9a-fA-F]+)           #  hex: "0x" followed by 1+ hex digits ("0x" is invalid)
|                          #    OR
(0[0-9]*)                  #  octal: '0' followed by 0+ digits [0-9] (0 is octal)

(Try it online!)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment