Regular Expressions 101

Community Patterns

Community Library Entry

1

Regular Expression
ECMAScript (JavaScript)

/
^([+-]?(?:NaN|Infinity|0(?:[bB][01](?:_?[01]+)*|[oO]?[0-7](?:_?[0-7]+)*|[xX][0-9a-fA-F](?:_?[0-9a-fA-F]+)*)|(?:(?:0|0(?:[0-9](?:_?[0-9]+)*)?[89](?:[0-9](?:_?[0-9]+)*)?|[1-9](?:_?[0-9]+)*)(?:\.(?:[0-9](?:_?[0-9]+)*)?)?|\.[0-9](?:_?[0-9]+)*)(?:[eE][+-]?[0-9](?:_?[0-9]+)*)?)|-?(?:0(?:[bB][01](?:_?[01]+)*|[oO][0-7](?:_?[0-7]+)*|[xX][0-9a-fA-F](?:_?[0-9a-fA-F]+)*)?|[1-9](?:_?[0-9]+)*)n)$
/
gm

Description

Should match any valid JavaScript number literal incl. bigint.

See EDIT 4 in this StackOverflow answer by me for matching JS numbers.

open in regex101 editor - example matches and unit tests
Regulex - colored graph
Regexper - slightly smaller and less colored graph

  • +/- Infinity and NaN
  • _ as numerical separator between any two digits
  • Number
    • leading/trailing . (decimal point)
    • leading 0s
      • [!] may be interpreted as octal (see below)
    • prefix
      • 0b binary
        • no . or scientific notation
      • 0o octal
        • [!] also implicit with leading 0 and when all digits (before any .) are below 8
        • no . or scientific notation
      • 0x hexadecimal
        • no . or scientific notation
          • [!] the E in scientific notation will be part of the hexadecimal number
  • BigInt
    • explicit via suffix n
    • no leading 0s except after a 0o/0x/0b prefix
    • no +, ., or scientific notation

Note, Number() (parsing from a string) allows leading/trailing whitespace, but not _, and leading 0s are not an implicit octal prefix, (and ofc no BigInt suffix)

Submitted by MAZ01001 - 9 months ago (Last modified 6 months ago)