Regular Expressions 101

Community Patterns

Match int and float numbers in polynomial

0

Regular Expression
ECMAScript (JavaScript)

/
([+-]?)\s*(?:(?:(?:[^.([{]?(\d+))|(\d+\.\d+(?!\w+)))(?!\w+|\.))(?![([{])
/
g

Description

I created this regex to match all integers and floats in polynomials.

This regex MATCHES:

  1. all integers
  2. all floats

All of the above + " not followed by "

  1. open parenthesis
  2. letters

GROUPS returned:

  1. SIGN: the sign of the integer or float matched, and empty string is returned if the sign is not provided
  2. INT: matches this group if the number is an integer
  3. FLOAT: matches this group if the number is a float

Note:

  1. the name of the groups are up to you, however "sign, int and float" are the most appropriate
  2. if the number is an integer, the float group (3) will NOT be matched
  3. if the number is a float, the integer group (2) will NOT be matched

so be careful when dealing with the order of the groups returned

Probably I'll create another version where it doesn't matter if the number returned int or float, but I think I'll leave it as it is because it's more precise.

Submitted by Giuseppe Tavella - 7 years ago