jehrhardt
Best way to build a parser
I want parse some text based format and I found two solutions for building a parser:
- Use Erlang’s built in leex and yecc, which are easy to use in Elixir.
- Use parser combinators like Nimble_parsec.
What is preferred way to parse text in Elixir? And why?
Marked As Solved
david_ex
In my (pretty limited) experience, I would go with:
- leex and yecc if your text is rigidly structured and follows some sore of grammar (e.g. it’s a DSL, config file, source code, etc.)
- NimbleParsec if your text is semi-structured (e.g. records where the schema wasn’t enforced and there are deviations) and you want to extract structured information from it
Basically, if your “rules” have a bunch of “that’s not always true” cases (e.g. "an email address usually follows the person’s name, but sometimes there’s a phone number instead’) I would go with NimbleParsec because it’s easier to manage the complexity (by combining sub-parsers).
Of course, you can also handle the variety of corner cases in the grammar given to leex and yecc, but in my experience the grammar size explodes pretty quickly and makes it challenging to keep in your head.
Also, if your case is simple you could get away with using just Elixir’s pattern matching on strings ("foo " <> rest_of_string"), here’s a description of the idea Redirect
Also Liked
jehrhardt
In my case, I want to parse some Python code to annotate it. Since there is a complete Python grammar available, I will go for leex and yecc.
Thanks for the explanation.
Qqwy
@david_ex’s answer is a great and simple ‘Tl;Dr’ one. For parsing Python code, going the route of Leex/Yecc definitely makes sense.
If you want a more in-depth question/anwer about when to use Parser Combinators and when to use Parser Generators, then this was a question I dwelled on ~2.5 years ago for quite a significant amount of time. You might enjoy reading my StackOverflow Question + Answer on this matter.
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance










