最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - RegEx to match only numbers incorrectly matching - Stack Overflow

programmeradmin2浏览0评论

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.

Share Improve this question asked Apr 19, 2013 at 20:56 SpencerSpencer 4,15810 gold badges34 silver badges43 bronze badges 4
  • 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
Add a ment  | 

3 Answers 3

Reset to default 4

The 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) );
发布评论

评论列表(0)

  1. 暂无评论