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:
-module(a).
-compile(export_all).
find(String, Map) ->
I = maps:iterator(Map),
match_for(String, I).
match_for(String, I) ->
case maps:next(I) of
none -> %% then you have reached the end of the Map
no_keys_in_map_matched_string;
{RegExKey, Val, NewI} ->
case re:run(String, RegExKey) of
nomatch -> match_for(String, NewI); %% continue iterating over the Map looking for a match
{match, _} -> Val %% found a match, so return the associated value
end
end.
2条答案
按热度按时间afdcj2ne1#
对于这种情况,不必须使用
map
。其思想是使用regex来查找与输入匹配的键,然后返回Map的值。未优化版本使用re:run/2
,而不编译模式。优化版本可以通过在使用之前编译一次regex模式来实现。
在Erlang shell中粘贴以上任何代码都将生成
"v1"
。上面的代码假设一个输入可以有多个匹配的模式,但是只有第一个模式会作为输出输出。
z31licg02#
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: