Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegEx match a number at the end of a string

I'm trying to match a number at the end of a string, using a regex. For example, the string might look like:

var foo = '101*99+123.12'; // would match 123.12
var bar = '101*99+-123';   // would match -123
var str = '101*99+-123.';  // would match -123.

This is what I've got so far, but it seem to match the entire string if there is no decimal point:

foo.match(/\-?\d+.?\d+?$/);

I take this to mean:

  • \-?: optional "-" symbol
  • \d+: 1 or more digits
  • .?: optional decimal point
  • \d+?: optional 1 or more digits after decimal point
  • $: match at the end of the string

What am I missing?

like image 994
Phil Avatar asked Jun 13 '13 21:06

Phil


1 Answers

. matches any character. You need to escape it as \.

Try this:

/-?\d+\.?\d*$/

That is:

-?           // optional minus sign
\d+          // one or more digits
\.?          // optional .
\d*          // zero or more digits

As you can see at MDN's regex page, +? is a non-greedy match of 1 or more, not an optional match of 1 or more.

like image 178
nnnnnn Avatar answered Sep 28 '22 05:09

nnnnnn