Jack Sobocinski
Jack Sobocinski

Reputation: 33

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!

Upvotes: 3

Views: 329

Answers (2)

rlefevre
rlefevre

Reputation: 174

You need a function returning a Parser String. You could use the variable function:

block : Parser (List String)
block =
    Parser.sequence
        { start = "{{"
        , separator = ""
        , end = "}}"
        , spaces = spaces
        , item =
            Parser.variable
                { start = Char.isAlphaNum
                , inner = Char.isAlphaNum
                , reserved = Set.empty
                }
        , trailing = Optional
        }

Example:

> Parser.run block "{{foo bar baz}}"
Ok ["foo","bar","baz"]
    : Result (List Parser.DeadEnd) (List String)

Upvotes: 0

Igor Drozdov
Igor Drozdov

Reputation: 15045

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.

Upvotes: 6

Related Questions