Erlang地图密钥模式匹配
我对Erlang更新,我有一个像#{“ a/。+”:“ v1”,“ b/c/+”:“ v2”}的地图,
我想通过输入键获得值“匹配” A /.+”并获取“ V1”。
当键确切的时,并且输入密钥是正则是REGEX,我该如何实现它。
I am newer to erlang, I have a map like #{"a/.+":"v1", "b/c/.+": "v2"}
I want to get value by input key like "a/d" to match "a/.+" and get "v1".
It easy to pattern when key is exactly and input key is regex, how can I implement it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在这种情况下,您 必须使用
地图
。这个想法是使用Regex查找与输入的关键匹配,然后返回映射的值。非优化版本正在使用
re:run/2
而无需编译模式。优化的版本可以通过在使用之前对正则态度图案进行编译。
在Erlang Shell中粘贴上述任何代码都会产生
“ V1”
。上面的代码假定一个输入可以具有多个匹配的模式,但是只有第一个输入将作为输出打印。
For this case, you don't have to use
map
. The idea is to use regex to find which key match with the input, and then return the mapped value.The un-optimized version is using
re:run/2
without compiling the pattern.The optimized version can be achieved by compiling the regex pattern once before using them.
Pasting any of above codes in Erlang shell will yield
"v1"
.Above code assumes that one input can have multiple matched pattern, but only the first one will be printed as output.
如果要在地图中找到与字符串匹配的所有键,则需要在整个地图上迭代:
a.erl:
在shell中:
如果地图中只有一个键可以匹配您的字符串,则找到匹配项后,您可以在地图上停止迭代:
a.erl:
在外壳中:
If you want to find all the keys in the map that match your string, you will need to iterate over the whole map:
a.erl:
In the shell:
If there is only one key in the map that will match your string, then you can stop iterating over the map as soon as you find a match:
a.erl:
In the shell: