RegExp spec question

Andrea Giammarchi andrea.giammarchi at gmail.com
Wed Jul 16 16:25:10 PDT 2014


you can also use this code ... like today, with every browser, and right
away ...


```javascript

function match(regex, haystack){
  var result = [], g = regex.global, match;
  do { match = regex.exec(haystack) }
  while(match && result.push(match) && g);
  if (!g) regex.lastIndex = 0;
  return result;
}

var input = "I have 5 dogs, 3 cats, and 49 ants.";

match(/\d+/, input)
match(/\d+/g, input)

```

Best Regards


On Wed, Jul 16, 2014 at 1:01 AM, Frankie Bagnardi <f.bagnardi at gmail.com>
wrote:

> You could wrap it in an iterator :-)
>
> http://www.es6fiddle.net/hxoczoqg/
>
> ```javascript
> function* match(regex, haystack){
>   var {source, ignoreCase} = regex;
>   var newRegex = new RegExp(source, ignoreCase ? 'gi' : 'g');
>   var m = null;
>   while (m = newRegex.exec(haystack)) {
>   yield m;
>   }
> }
>
> var input = "I have 5 dogs, 3 cats, and 49 ants.";
>
> for (let num of match(/\d+/, input)) {
> console.log(num);
> }
> ```
>
>
>
> On Wed, Jul 16, 2014 at 12:53 AM, Axel Rauschmayer <axel at rauschma.de>
> wrote:
>
>> Yes, the /g flag is confusing, because the regular expression kind of
>> turns into an iterator. I’d much prefer an actual iterator-based API that
>> doesn’t mutate the regular expression.
>>
>> On Jul 16, 2014, at 9:26 , Alex Vincent <ajvincent at gmail.com> wrote:
>>
>> r = /\u0020+$/g; p = r.exec("  "); q = r.exec("  "); JSON.stringify([p,
>> q])
>> // "[[\"  \"],null]"
>>
>> Why does calling exec the second time generate null?  When I try the
>> regular expression without the /g flag, I get:
>> // "[[\"  \"],[\"  \"]]"
>>
>>
>>
>> --
>> "The first step in confirming there is a bug in someone else's work is
>> confirming there are no bugs in your own."
>> -- Alexander J. Vincent, June 30, 2001
>> _______________________________________________
>> es-discuss mailing list
>> es-discuss at mozilla.org
>> https://mail.mozilla.org/listinfo/es-discuss
>>
>>
>>  --
>> Dr. Axel Rauschmayer
>> axel at rauschma.de
>> rauschma.de
>>
>>
>>
>>
>> _______________________________________________
>> es-discuss mailing list
>> es-discuss at mozilla.org
>> https://mail.mozilla.org/listinfo/es-discuss
>>
>>
>
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20140716/dc62fdb2/attachment.html>


More information about the es-discuss mailing list