Skip to content

Commit

Permalink
RegExp#exec now does successive matching.
Browse files Browse the repository at this point in the history
- Properly set the lastIndex value.
- Make sure count PCRE wrapper is non-negative.
  • Loading branch information
ndreynolds committed Mar 7, 2013
1 parent 780f62c commit 716662f
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 6 deletions.
2 changes: 1 addition & 1 deletion src/regexp.c
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ fh_regexp(char *str, char *pattern, int *count, int offset, bool caseless)
output_vector, regexp_vector_len);

if (count != NULL)
*count = rc;
*count = rc > 0 ? rc : 0;

pcre_free(regexp);

Expand Down
5 changes: 3 additions & 2 deletions src/runtime/lib/RegExp.c
Original file line number Diff line number Diff line change
Expand Up @@ -70,15 +70,16 @@ regexp_proto_exec(js_val *instance, js_args *args, eval_state *state)
matched = true;
}

char *substr = fh_str_slice(str->string.ptr, matches[0], matches[1]);

if (global)
fh_set(instance, "lastIndex", JSNUM(i));
fh_set(instance, "lastIndex", JSNUM(matches[0] + strlen(substr)));

js_val *res = JSARR();

fh_set(res, "index", JSNUM(matches[0]));
fh_set(res, "input", str);

char *substr = fh_str_slice(str->string.ptr, matches[0], matches[1]);
fh_set(res, "0", JSSTR(substr));

for (i = 1; i <= count; i++) {
Expand Down
19 changes: 16 additions & 3 deletions test/test_regexp_global.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,7 @@ var assertEmptyRegExp = function(r, cmp) {
assertEquals(r.ignoreCase, cmp.ignoreCase);
};

var test = function(name, f) {
f();
};
var test = function(name, f) { f(); };


// ----------------------------------------------------------------------------
Expand Down Expand Up @@ -80,6 +78,21 @@ test('RegExp#exec(str)', function() {
assertEquals('....abc....', result.input);
assertEquals(4, result.index);
assertEquals(1, result.length);

// Adapted example from MDN docs:
var myRe = /ab*/g;
var str = "abbcdefabh";
var myArray;
result = [];
while ((myArray = myRe.exec(str)) !== null) {
result.push(myRe.lastIndex);
result.push(myArray[0]);
}

assertEquals(3, result[0]);
assertEquals('abb', result[1]);
assertEquals(9, result[2]);
assertEquals('ab', result[3]);
});

test('RegExp#test(str)', function() {
Expand Down

0 comments on commit 716662f

Please sign in to comment.