Search code examples
parsingelm

Elm Parser cannot Return String Inside Curly Braces


I am new to the Elm parser library and I am trying to make a move away from using regex. I need to parse a string and return a list of strings for each string inside double curly braces like so {{return this}} I am using the Parser.sequence function and this is my code

block : Parser (List String) 
block = 
  Parser.sequence
    { start = "{{"
    , separator = ""
    , end = "}}"
    , spaces = spaces
    , item = getSource
    , trailing = Optional
    }

My question is, What should I do in the item field to return the string in between the curly braces. Thanks!


Solution

  • What about creating your own parser for a word?

    word : Parser String
    word =
      getChompedString <|
        succeed ()
          |. chompIf Char.isAlphaNum
          |. chompWhile Char.isAlphaNum
    

    It actually chomps alphanum characters, so {{return textABC123}} will result as Ok ["return","textASD234"]. For {{return text}} Char.isLower is sufficient.

    Then you can use it in sequence instead of getSource (since getSource also chomps } characters, which is not suitable in the current situation):

    block : Parser (List String) 
    block = 
      Parser.sequence
        { start = "{{"
        , separator = ""
        , end = "}}"
        , spaces = spaces
        , item = word
        , trailing = Optional
        }
    

    Here is an ellie-app example, which demonstrates it.