'Getting values of named subpatterns in erlang
Hi I have a following regexp and value
2> re:run("first second", "^(?<foo>\\w+) (?<bar>\\w+)$", [{capture, [foo, bar], list}]).
{match,["first","second"]}
3>
Here I matched foo with "first" and bar with "second". The problem is in my app (url mapper), I do not know how many named sub-patterns there will be and what their names will be. So I want them to be matched something like
2> re:magic_run("first second", "^(?<foo>\\w+) (?<bar>\\w+)$" ).
{match,[{foo, "first"},{bar, "second"}]}
My concern is not the output format. I want to able to match values with subpattern names. Is there a way to pair the values with subpatterns?
Solution 1:[1]
For people who are interested in this in 2022. You can get the values for the named capture groups like this:
1> re:run("cat",".+(?P<A>at)", [{capture,['A'],list}]).
{match,["at"]}
2> re:run("catlololo",".+(?P<A>at)(?P<C>lol.+)", [{capture,['A','C'],list}]).
{match,["at","lololo"]}
The names of the capture groups after the capture
specify which values to read.
ref: https://www.erlang.org/doc/man/re.html#run-3
Solution 2:[2]
If your string is not regular, do not use regular expressions. Especially in your case I would highly recommend using a String.split()-method of some kind (never programmed Erlang, but I think someone might have implemented this).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Swagat Parida |
Solution 2 | Lucas Hoepner |