tm1rbrt tm1rbrt - 1 month ago 10
Javascript Question

Regex exec only returning first match

I am trying to implement the following regex search found on golfscript syntax page.

var ptrn = /[a-zA-Z_][a-zA-Z0-9_]*|'(?:\\.|[^'])*'?|"(?:\\.|[^"])*"?|-?[0-9]+|#[^\n\r]*|./mg;
input = ptrn.exec(input);


Input is only ever the first match of the regexp. for example:
"hello" "world"
should return
["hello", "world"]
but it only returns
["hello"]
.

Answer
var ptrn = /[a-zA-Z_][a-zA-Z0-9_]*|'(?:\\.|[^'])*'?|"(?:\\.|[^"])*"?|-?[0-9]+|#[^\n\r]*|./mg;
var match;
while ( ( match = ptrn.exec(input) ) != null )
{
    alert( match );
}

This will alert all matches.