shahryarjb

shahryarjb

What is the best way for Parsing a string and convert to map

Hello, I wanted to use the NimbleParsec library to convert a string into the map I need. But I think I got it wrong and this is more for me to equle with something and not to make the output I need like regex. it’s true?

For example I have this string

"sanitize(trim, lowercase) validate(not_empty, max_len = 20)"
# And I need something like this:
# Output: %{sanitize: ['trim', 'lowercase'], validate: ['not_empty', {'max_len', '20'}]}

It should be a bit dynamic for example:

"sanitize(trim, lowercase, downcase, replace= T) validate(not_empty, max_len = 20, not_integer)"
# Output: %{sanitize: ['trim', 'lowercase', 'downcase', {'replace', 'T'}], validate: ['not_empty', {'max_len', '20'}, 'not_integer']}

Now, without regex is there a good way? or NimbleParsec can create something like this?

It should be noted I have many items for each part like `trim, lowercase, downcase and etc..

Thank you in advance

Most Liked

hst337

hst337

The shortest solution is

for line in String.split(input, ")"), do: Code.string_to_quoted!(line <> ")")
LostKobrakai

LostKobrakai

NimbleParsec is not regex. It’s not “searching” through your input.

A parser works by going though the input string front → end and at each step you need to define what can be matched next. In your example you tell it to match either "validate" or "sanitize". It starts from the front, finds "sanitize" and then the next char is (, which matches neither of your expected values, so parsing halts.

NimbleParsec — NimbleParsec v1.3.1 has an example of something similar, parsing things wrapped in " instead of parenthesis.

cmo

cmo

With NimbleParsec, you create rules for the things you want to parse and then define a parser, e.g parsing a gmail-like search string. Should be pretty straight forward to parse your text format.

  ...

  field =
    choice([
      string("message:") |> replace(:message),
      string("user:") |> replace(:user),
      string("ip:") |> replace(:ip)
    ])
    |> ignore(optional(whitespace))

  param =
    repeat(
      lookahead_not(concat(optional(whitespace), choice([field, value_field, time_field])))
      |> optional(whitespace)
      |> utf8_string([not: ?\s], min: 1)
    )
    |> ignore(choice([whitespace, eos()]))
    |> post_traverse(:join)

  ...

  defparsec :parse_search_string,
            ignore(optional(whitespace))
            |> times(
              choice([
                concat(field, param),
                value_field_param,
                time_field
              ])
              |> post_traverse(:group)
              |> ignore(optional(whitespace)),
              
hst337

hst337

NimbleParsec is okay for this task. You can handroll the parser yourself, since it is pretty simple parser with only two different states.

D4no0

D4no0

I think he means using lex/yacc, in theory it should be very easy and pretty versatile implementation.

Where Next?

Popular in Questions Top

jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod -- where is this set? Thanks.
New
sergio
In Ruby, I can go: User.find_by(email: "foobar@email.com").update(email: "hello@email.com") How can I do something similar in Elixir? ...
New
_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
New
tduccuong
Hi, is there any work on GUI with Elixir, that is similar to Electron/Javascript? My idea is to bundle Phoenix and BEAM into a single se...
New
Jim
As a follow up to my earlier question: I have the code compiling and running but not getting a successful login from the rest server. ...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
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
johnnyicon
Hi all, I've just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I'm trying to use Postg...
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New

Other popular topics Top

Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
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
axelson
This post is a wiki (feel free to hit the edit button near the bottom right of this post to add your own changes!) This post collects co...
239 45766 226
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
malloryerik
Hi, this is for people who, like me, have had some friction using .html.heex templates in VSCode. The solution seems to be, in a hyphena...
New
johnnyicon
Hi all, I've just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I'm trying to use Postg...
New
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New

We're in Beta

About us Mission Statement