Match a portion of a string using regex


#1

Hey guys, anyone know a way match a portion of a string with a regex expression?

attributes.modelId is of string type and is a string:

let length = String.length(attributes.modelId);
let lastIndex = String.rindex(attributes.modelId, ':');
let newModelId = String.sub(attributes.modelId, lastIndex + 1, length - (lastIndex + 1)) |> int_of_string

I was also thinking of doing:

attributes.modelId |> Js.String.match([%re "/\d+/"]) |> result => Js.log(result[0])

but trying to do result[0] gives me:

This has type:
    option(array(Js.String.t))
  But somewhere wanted:
    array('a)

Any tips?


#2

I think I figured it out.

I have to do something like:

    attributes.modelId 
      |> Js.String.match([%re "/\\d+/"])
      |> result => switch(result) {
          | None => -1
          | Some(result) => {
            result[0] |> int_of_string
          };
        },

I believe I need to use a switch here because it expects an option and for that I need to handle both cases, none and some. If anyone has any better way to do it, feel free to chime in - I appreciate any feedback


#3

Don’t use pipes with lambda


#4

Hi Khady, may I ask specifically why? Also, do you mean within the

Some(result) => {

lambda? Or is this the whole entire switch?