Nom passing repeating patterns

I think I understand nom in a basic manner but I am having trouble finding examples how to deal with repeating patterns.

For example lets say I were passing a text file line by line and the first line had to be


tag_name1:tag_val1 tag_name2:tag_val2 tag_name3:tag_val3 ...

ie a number of tags defined as name:value pairs separated by spaces

Lets assume name and val are strings for simplicity.

I can parse each tag with something like

separated_pair(alphanumeric1, tag(":"), alphanumeric1)(i)

However, I can't seem to workout how I can I use nom to parse one or more of these tags up until a newline and return a tuple of the results.
I don't know the number of tags before hand.


You can't parse a tuple (since the number of elements would need to be known at compile time,) but you can parse a Vec using nom::multi::separated_list:

let p = separated_pair(alphanumeric1, tag(":"), alphanumeric1);
separated_list(tag(" "), p)(i) 

You can replace tag(" ") with space1 if you want to support arbitrary amounts of space between the pairs.

The nom combinators for repeated parsing are in nom::multi.

1 Like

Ah Thanks.
I find it hard to know where to start with nom sometimes.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.