How to remove the string concerned from the original string

Hello, I have a string which is my Url, the string is:

125-1jump-test-for12-test

now I want to remove 125- from the string by this regex

  def get_number_of_url(url_string) do
    Regex.match?(~r/^(\d+)/, "#{url_string}")
  end

I need it to be without number before - DASH, how can I edit this, I want to remove the string which the regex finds and first DASH after that ?

for example:

1jump-test-for12-test

if there are 2 125-, how will I do ? like this:

125-1jump-test-for12-test-125-

Probably something like this:

def strip_leading_number(string) when is_binary(string) do
  case Regex.run(~r/^\d+-/, string) do
    [match] -> string |> String.replace(match, "")
    _ -> string
  end
end
3 Likes

thank you, but that has a bug when my url is like this

125-1jump-test-for12-test-125-

it removes all 125- like this:

"1jump-test-for12-test-"

but I want this:

"1jump-test-for12-test-125-"

I thought your edit meant you wanted to remove all of them, sorry.

In that case, it’s even simpler:

def strip_leading_number(string) when is_binary(string) do
  string |> String.replace(~r/^\d+-/, "")
end
3 Likes

@shahryarjb you could also use:

iex> string = "125-1jump-test-for12-test-125-"
iex> Regex.replace(~r/^\d+-/, string, "")
"1jump-test-for12-test-125-"

@david_ex do you know if there are any big differences between the two functions? (will try to check the source later today)

1 Like

There’s no difference: String.replace/4 proxies the call to Regex.replace/4. See code

FYI, when looking at the Elixir docs for a given function (e.g. Regex.replace/4), you can click on </> in the top right where the function head is displayed and it will take you to the relevant location in the source code.

4 Likes

nice! thanks for the tip!

1 Like