Regular Expressions 101

Community Patterns

Your search did not match anything

Community Library Entry

1

Regular Expression
ECMAScript (JavaScript)

/
^([+-]?(?:NaN|Infinity|0(?:[bB][01](?:_?[01]+)*|[oO][0-7](?:_?[0-7]+)*|[0-7]+|[xX][0-9a-fA-F](?:_?[0-9a-fA-F]+)*)|(?:(?:0|0[0-9]*[89][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/bigint literal.

See 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 (except with leading 0s)
  • Number
    • leading/trailing . (decimal point)
    • leading 0s
      • [!] interpreted as octal when all digits are less than 8 (then . or scientific notation will error)
      • [!] doesn't allow numerical separator (in the integer part; even with digits above 7)
    • prefix
      • 0b binary
        • no . or scientific notation
      • 0o octal
        • no . or scientific notation
      • 0x hexadecimal
        • no . or scientific notation
  • 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 and scientific notation, but not _, and leading 0s are not an implicit octal prefix, (and ofc no BigInt suffix)

Submitted by MAZ01001 - 2 years ago (Last modified 2 months ago)