Regular expression for selecting items from a transformation matrix

I have a style conversion string defined as follows:

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

How can I create an array containing the elements of this matrix? Any tips on how to write a regex for this?

+6
source share
4 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) 
+7
source

Here is one way. Highlight some of the numbers with a 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"] 
+3
source

Try the following:

 /^matrix\(([+\-\d.]+), ([+\-\d.]+), ([+\-\d.]+), ([+\-\d.]+), ([+\-\d.]+), ([+\-\d.]+)\)$/ .exec(str).slice(1); 

Demo

+1
source

Maybe something like this:

 var string = "matrix(0.312321, -0.949977, 0.949977, 0.312321, 0, 0)"; var array = string.replace(/^.*\((.*)\)$/g, "$1").split(/, +/); 

Note that in this way the array will contain a string. If you want the real number to be simple, this is:

 array = array.map(Number); 

Your js engine must support map or have a pad for it (of course, you can also convert them manually).

+1
source

Source: https://habr.com/ru/post/919195/


All Articles