BSWard
BSWard

Reputation: 25

First and Last Number in String?

I'm really struggling to extract two numbers from a string using Regex. The numbers can be positive, negative or 0. I have extremely limited experience of Regex.

The string always takes a format similar to:

"rotateX(-90deg) rotateY(-90deg)"

My best attempts are the following. This first approach gets me the first integer but does not get me the + / - sign:

var rx = string.replace( /(^.+\D)(\d+)(\D.+$)/i,'$2')

And, the following seems to get me the second, potentially as an element in an array but also does not get me the +/- sign:

var ry = string.match(/(\d+)/i);

Upvotes: 0

Views: 711

Answers (1)

Joe
Joe

Reputation: 15802

You can just look for [+ or - sign] followed by [one or more numbers] like this:

"rotateX(-90deg) rotateY(-90deg)".match(/([+-]?\d+)/g); // ["-90", "-90"]

It just returns an array of all matches, which you can check length of with .length to make sure it's got 2 things in it, then access them with [0] and [1].

Upvotes: 4

Related Questions