用于从变换矩阵中选择元素的正则表达式

时间:2012-06-27 23:18:11

标签: javascript css regex arrays css3

我有一个以下列方式给出的样式变换字符串:

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

如何形成包含此矩阵元素的数组?有关如何为此编写正则表达式的任何提示吗?

4 个答案:

答案 0 :(得分:7)

我会这样做......

// 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)

答案 1 :(得分:4)

这是一种方式。使用正则表达式解析数字部分,然后使用split()方法:

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"]

答案 2 :(得分:1)

试试这个:

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

DEMO

答案 3 :(得分:1)

可能是这样的:

var string = "matrix(0.312321, -0.949977, 0.949977, 0.312321, 0, 0)";

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

请注意,这样数组将包含字符串。如果你想要实数,一个简单的方法是:

array = array.map(Number);

你的js引擎需要支持map或者有一个垫片(当然你也可以手动转换它们)。