I'm trying to use a regular expression in JavaScript to match a number or a number containing a decimal. The regular expression looks like [0-9]+ | [0-9]* \. [0-9]+
.
However, for some reason this '1A'.match(/^[0-9]+|[0-9]*\.[0-9]+$/)
incorrectly finds a match. I'm not sure which part of the expression is matching the A
.
I'm trying to use a regular expression in JavaScript to match a number or a number containing a decimal. The regular expression looks like [0-9]+ | [0-9]* \. [0-9]+
.
However, for some reason this '1A'.match(/^[0-9]+|[0-9]*\.[0-9]+$/)
incorrectly finds a match. I'm not sure which part of the expression is matching the A
.
-
1
'1A'.match(/^([0-9]+|[0-9]*\.[0-9]+)$/)
group it – user2264587 Commented Apr 19, 2013 at 20:57 - Looks like something that could be handled by ´parseFloat´ Without any need for a RegExp – Xotic750 Commented Apr 19, 2013 at 20:59
- Why do you need that? Is that for validating input or what? – VisioN Commented Apr 19, 2013 at 21:00
- I'm writing a tokenizer for CSS3 based on w3/TR/css3-syntax/#tokenization. – Spencer Commented Apr 19, 2013 at 21:13
3 Answers
Reset to default 4The problem is your alternation. This is what it says:
^[0-9]+ # match an integer at the start
| # OR
[0-9]*\.[0-9]+$ # match a decimal number at the end
So the first alternative matches.
You need to group the alternation:
/^(?:[0-9]+|[0-9]*\.[0-9]+)$/
The ?:
is an optimisation and a good habit. It suppresses capturing which is not needed in the given case.
You could get away without the alternation as well, though:
/^[0-9]*\.?[0-9]+$/
Or even shorter:
/^\d*\.?\d+$/
'1A'.match(/^[0-9]+|[0-9]*\.[0-9]+$/)
finds a match because it is a union of:
^[0-9]+
and
[0-9]*\.[0-9]+$
where the first matches.
to avoid this, group them: ^([0-9]+|[0-9]*\.[0-9]+)$
and try this:
'1A'.match(/^([0-9]+|[0-9]*\.[0-9]+)$/) === null
alternatively:
function matchExacly(str, regex) {
var tmp = str.match(regex);
return tmp ? tmp[0] === str : false;
}
matchExacly('1A', /[0-9]+|[0-9]*\.[0-9]+/) === false
matchExacly('1', /[0-9]+|[0-9]*\.[0-9]+/) === true
Maybe I am at the wrong place but if you use regex just for validating numeric values, why not to use faster alternatives, as the following:
var isNumber = ( +n === parseFloat(n) );