Gizra / elm-compat-019 / Regex018

Elm 0.19 made several improvements to the API.

Some of the old API cannot be re-implemented for Elm 0.19.


type HowMany
    = All
    | AtMost Basics.Int

HowMany is used to specify how many matches you want to make. So replace All would replace every match, but replace (AtMost 2) would replace at most two matches (i.e. zero, one, two, but never three or more).

regex : String -> Regex

Create a Regex that matches patterns as specified in JavaScript.

Be careful to escape backslashes properly! For example, "\w" is escaping the letter w which is probably not what you want. You probably want "\\w" instead, which escapes the backslash.

In Elm 0.18, an invalid input string would crash the runtime. It is not possible to reproduce this behaviour in Elm 0.19. Thus, if given invalid input, we will instead return a Regex that never matches anything.

find : HowMany -> Regex -> String -> List Regex.Match

Find matches in a string:

find (AtMost 2) (regex ",") "a,b,c,d,e"
    |> List.map .index
--> [1,3]

find (AtMost 2) (regex ",") "a b c d e"
    |> List.map .index
--> []

find All
    (regex "[oi]n a (\\w+)")
    "I am on a boat in a lake."
    |> List.map .match
-->  ["on a boat", "in a lake"]


find All
    (regex "[oi]n a (\\w+)")
    "I am on a boat in a lake."
    |> List.map .submatches
--> [ [Just "boat"], [Just "lake"] ]

replace : HowMany -> Regex -> (Regex.Match -> String) -> String -> String

Replace matches. The function from Match to String lets you use the details of a specific match when making replacements.

replace All
    (regex "[aeiou]")
    (\_ -> "")
    "The quick brown fox"
-->  "Th qck brwn fx"

replace (AtMost 2)
    (regex "\\w+")
    (\{ match } -> String.reverse match)
    "deliver mined parts"
--> "reviled denim parts"

split : HowMany -> Regex -> String -> List String

Split a string, using the regex as the separator.

split (AtMost 1)
    (regex ",")
    "tom,99,90,85"
--> [ "tom", "99,90,85" ]

split All
    (regex ",")
    "a,b,c,d"
--> [ "a", "b", "c", "d" ]