2

I have a string like this: matrix(10, 0, 1, 0, -198, 23)

Then I need to match the arguments from that function and put in array:

var regexp = /.../gi
var match = regexp.exe('matrix(10, 0, 1, 0, -198, 23)');

console.debug(match) // must return: [10, 0, 1, 0, -198, 23]

I'm not very familiar with regular expression, but I think will be the fastest way to do the job.

split string is not possible in this case.

Performance test for the awnsers: http://jsperf.com/regexp-match-vs-string-split

4
  • What have you tried? Commented Jun 14, 2012 at 19:41
  • lot's of fail regular expressions.... Commented Jun 14, 2012 at 19:42
  • /[\+\-\d\s,]+/.exec( str ) ? Commented Jun 14, 2012 at 19:44
  • Or you searching for a str or do you just want the numbers? Commented Jun 14, 2012 at 19:48

2 Answers 2

5
'matrix(10, 0, 1, 0, -198, 23)'.match(/-?\d+/g)
Sign up to request clarification or add additional context in comments.

1 Comment

Sorry, but it fail, -198 has returned 198
1

Three steps:

  1. Use regex to get contents of parens
  2. replace the parens themselves and with nothing
  3. split on comma followed by 0 or more white space
var str = 'matrix(10, 0, 1, 0, -198, 23)',
    regex = /\(.*\)/,
    arr;

str = str.match(regex)[0];
str = str.replace(/[()]/g, '');
arr = str.split(/,\s+/);

​console.log(arr);​

4 Comments

it's not working... the first match returns null and the split don't exist on javascript as default...
SyntaxError: Unexpected token ILLEGAL
As I said in the question, split string isn't possible in this case. But your code work, the performance is poor, test for your self: jsperf.com/regexp-match-vs-string-split
In Chrome, at least, the performance of my solution is approximately equal to the accepted one. In addition, it's a general solution that doesn't just capture integer arguments. It will capture all arguments.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.