Update for 2021:
Due to the significant growth in lookbehind support, it is recommended to use a lookbehind-based solution like this:
/(?<!\w)\d*[.,]?\d+(?!\w)/gi # ASCII only
/(?<!\p{L})\p{N}*[.,]?\p{N}+(?!\p{L})/giu # Unicode-aware
You can see the regex demo here. Keep track of lookbehind and Unicode property class support on this page.
More Information
(?<![a-z])
- there should not be any ASCII letter (or any Unicode letter if using \p{L}
) immediately to the left
\d*[.,]?\d+
(?![a-z])
- there should not be any ASCII letter (or any Unicode letter if using \p{L}
) immediately to the right.
Original Answer
If you want to match standalone integer or float numbers with dot or comma as decimal separators, you can use the following pattern:
/(?:\b\d+[,.]|\B[.,])?\d+\b/g
Check out the regex demo here. The key point is that you cannot use a word boundary \b
before a .
because it will exclude matches like .55
(only 55
will be matched).
Details:
(?:\b\d+[,.]|\B[.,])?
- either of these alternatives:
\b\d+[,.]
- a word boundary (must include a non-word character before or start of string), then 1+ digits, followed by a .
or ,
|
- or
\B[.,]
- a position that is not a word boundary (only includes a non-word character or start of string) followed by a .
or ,
\d+
- 1+ digits
\b
- a word boundary.
const regex = /(?:\b\d+[,.]|\B[.,])?\d+\b/g;
const str = `.455 and ,445 44,5345 435.54 4444
1
1,2
1.5-4
(1+3)
=1;
FF3D
3deg`;
console.log(str.match(regex));
If you also need to add support for exponents, you can use this pattern:
/(?:\b\d+[,.]|\B[.,])?\d+(?:e[-+]?\d+)?\b/ig