I am working on some Elixir coding challenge that requires Regex solution and encountered this following code:
defmodule Solution do
def remove(some_string)
String.replace(some_string, ~r/!(?!!*$)/, "")
end
end
Solution.remove("!Hi!!!") #=> "Hi!!!"
Solution.remove("Hi!") #=> "Hi!"
Solution.remove("Hi") #=> "Hi"
It removes exclamation mark that are not at the end.
My question is, I do not understand what /!(?!!*$)/
line does. I believe this part of Regex is not Elixir-specific. I know that !*$
means that zero or more !
at the end of the String. What does the entire regex do in plain English?
Additionally:
What does ?!
... do? (I thought ?
means zero or more, but why is it before an exclamation mark?)
Why is there an exclamation mark before the parentheses !(
...?