cuadraman
cuadraman

Reputation: 15164

How to String matchAll in Reason?

I'm trying to replicate what I would do in javascript with matchAll()

  const names = [
    ...withoutSlashes.matchAll(/(?<=Pos\. \d+ \- )(.*?)(?=","Importe)/g),
  ];

I see Reason has Js.String.match but I can't find the matchAll. I guess it's because matchAll is a newer ecmascript.

Any hint on which would be a good way to do a performant matchAll? or is there a specific Reason feature that I'm missing?

Upvotes: 1

Views: 217

Answers (2)

ryyppy
ryyppy

Reputation: 442

Based on the accepted answer I wanted to add a version that is following ReScript conventions. [@bs.send.pipe] is discouraged, and the ReScript language officially recommends the pipe-first operator (-> instead of |>).

like this:

[@bs.send]
external matchAll: (string, Js.Re.t) => Js.Array.array_like(array(string)) =
  "matchAll";

let matches: array(string) =
  matchAll("abc", [%re "/[a-c]/g"])->Js.Array.from;

Upvotes: 3

glennsl
glennsl

Reputation: 29116

You can bind to it yourself. The biggest problem with it is that it returns an iterator, which we also don't have bindings for. But we can use Js.Array.array_like('a) and then convert it to an array using Js.Array.from:

[@bs.send.pipe: string]
external matchAll: Js.Re.t => Js.Array.array_like(array(string)) = "matchAll";

let matches = "abc" |> matchAll([%re "/[a-c]/g"]) |> Js.Array.from;

Upvotes: 0

Related Questions