revati

revati

How to parse strings with NimbleParsec?

Hello.
i would like to parse strings (with nimble parsec i assume) that look something like this:

x(some.dot.split.values) → [x: [“some”, “dot”, “split”, “value”]]
y(some.x(dot).split.values) → [y: [“some”, [x: [“dot”]], “split”, “value”]]

maybe if it is easier to implement

x some.dot.split.values → [x: [“some”, “dot”, “split”, “value”]]
y some.(x dot).split.values → [y: [“some”, [x: [“dot”]], “split”, “value”]]

Idea is to have nested patterns, and dot split strings that should represent array

I found this, but i do not understand how perentacies are implemented there How do you write nested and recursive NimbleParsec parsers? - #4 by jakemorrison

Maybe someone knows. Thanks.

Marked As Solved

NduatiK

NduatiK

defmodule Parser do
  import NimbleParsec

  # Step 1: Define your smallest units
  # I've assumed here that the a word is a list of
  # more than one lowercase character
  # 
  # Match abc
  defparsecp(
    :word,
    times(ascii_char([?a..?z]), min: 1)
    |> reduce({List, :to_string, []})
  )

  # Step 2: Define a function as a a thing
  # that has a word followed by:
  # - an opening bracket
  # - a "chain of stuff"
  # - a closing bracket
  #
  # Match abc(___)
  defparsec(
    :function,
    parsec(:word)
    |> map({String, :to_atom, []})
    |> concat(
      ignore(string("("))
      |> concat(parsec(:chain))
      |> concat(ignore(string(")")))
      # Put the function arguments in a list
      |> wrap()
    )
  )

  # Match abc or abc(___)
  defparsecp(
    :function_or_word,
    choice([
      parsec(:function),
      parsec(:word)
    ])
  )

  # Step 3: Define the "chain" as a
  # word or function followed by a "."
  # delimited list of words or functions
  # 
  # Match abc.def or abc(___).def or abc(___).def
  defparsecp(
    :chain,
    parsec(:function_or_word)
    |> times(
      ignore(string("."))
      |> concat(parsec(:function_or_word)),
      min: 0
    )
  )

  def parse!(str) do
    # Only parse successfully if the entire string is consumed
    {:ok, result, "" = _unconsumed, %{}, {_, _}, _} =
      function(str)

    result
  end
end

Parser.parse!("x(some.dot.split.values)")
Parser.parse!("y(some.x(dot).split.values)")

Also Liked

jakemorrison

jakemorrison

Here is a library that supports parsing nested lists with parentheses: GitHub - cogini/http_structured_field: Elixir library to parse HTTP Structured Fields (RFC 8941)

Where Next?

Popular in Questions Top

senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
Tee
can someone please explain to me how Enum.reduce works with maps
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 record...
New
Werner
Hi, I’m using Ubuntu 18.04 and after updating to OTP-24.0 yesterday i have this warning when I run “mix local.hex”: 14:57:30.512 [warn] ...
New
vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list....
New
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
Exadra37
Sometimes I want to check if the input into a function is not a blank string. My first approach: defmodule Example do def do_stuff(s...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New

Other popular topics Top

shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
JakeBecker
TL;DR: I’ve just released an implementation of Microsoft’s IDE-independent Language Server Protocol for Elixir. It adds language support ...
1140 51847 244
New
William
I would like to know that is there any online source for learning Phoenix Framework for building E-Commerce Store? Any advantage on build...
New
sergio
I couldn’t find any guides that worked well with Phoenix 1.6.0 and esbuild. I hope this helps people test the waters and eases you into t...
New
lk-geimfari
What is most correct way to open, read and parse JSON file with poison? For example if we have example.json file in root of some projec...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lis...
New
beno
I will often find my self writing things similar to: case some_value do nil -> something() "" -> something() _ -> someth...
New
AstonJ
by Lance Halvorsen Elixir and Phoenix are generating tremendous excitement as an unbeatable platform for building modern web application...
460 27162 124
New
magnetic
Hey :wave:t3: Elixir community, I’ve been learning Elixir, and working on some side projects. My editor of choice is VSCode, and althoug...
New

We're in Beta

About us Mission Statement