Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for selecting elements from transform matrix

I have a string of style transform given in the following way :

matrix(0.312321, -0.949977, 0.949977, 0.312321, 0, 0)

How can I form an array containing elements of this matrix ? Any tips how to write regex for this ?

like image 523
mike_hornbeck Avatar asked Jun 27 '12 23:06

mike_hornbeck


2 Answers

I would do it like this...

// original string follows exactly this pattern (no spaces at front or back for example)
var string = "matrix(0.312321, -0.949977, 0.949977, 0.312321, 0, 0)";

// firstly replace one or more (+) word characters (\w) followed by `(` at the start (^) with a `[`
// then replace the `)` at the end with `]`
var modified = string.replace(/^\w+\(/,"[").replace(/\)$/,"]");
// this will leave you with a string: "[0.312321, -0.949977, 0.949977, 0.312321, 0, 0]"

// then parse the new string (in the JSON encoded form of an array) as JSON into a variable
var array = JSON.parse(modified)

// check it is correct
console.log(array)
like image 151
Billy Moon Avatar answered Sep 28 '22 06:09

Billy Moon


Here's one way. Parse out the numbers part with regex and then use the split() method:

var s = "matrix(0.312321, -0.949977, 0.949977, 0.312321, 0, 0)";
s.match(/[0-9., -]+/)[0].split(", "); // results in ["0.312321", "-0.949977", "0.949977", "0.312321", "0", "0"]
like image 36
Joseph Marikle Avatar answered Sep 28 '22 06:09

Joseph Marikle