当我编写进行文本解析的 Erlang 程序时,我经常遇到我喜欢使用正则表达式进行模式匹配的情况。
例如,我希望我能做这样的事情,其中 ~ 是一个“组成”的正则表达式匹配运算符:
my_function(String ~ ["^[A-Za-z]+[A-Za-z0-9]*$"]) ->
....
我知道正则表达式模块(re),但AFAIK你不能在模式匹配或守卫时调用函数。
另外,我希望匹配字符串可以以不区分大小写的方式完成。这很方便,例如,在解析 HTTP header 时,我想做这样的事情,其中“Str ~ {Pattern, Options}”表示“使用选项选项将 Str 与模式模式匹配”:
handle_accept_language_header(Header ~ {"Accept-Language", [case_insensitive]}) ->
...
两个问题:
最佳答案
除了提前运行正则表达式然后对结果进行模式匹配之外,您实际上别无选择。这是一个非常简单的示例,它接近我认为您所追求的,但它确实存在您需要重复正则表达式两次的缺陷。您可以通过使用宏在一个地方定义每个正则表达式来减轻痛苦。
-module(multire).
-compile(export_all).
multire([],_) ->
nomatch;
multire([RE|RegExps],String) ->
case re:run(String,RE,[{capture,none}]) of
match ->
RE;
nomatch ->
multire(RegExps,String)
end.
test(Foo) ->
test2(multire(["^Hello","world$","^....$"],Foo),Foo).
test2("^Hello",Foo) ->
io:format("~p matched the hello pattern~n",[Foo]);
test2("world$",Foo) ->
io:format("~p matched the world pattern~n",[Foo]);
test2("^....$",Foo) ->
io:format("~p matched the four chars pattern~n",[Foo]);
test2(nomatch,Foo) ->
io:format("~p failed to match~n",[Foo]).
关于regex - 如何使用正则表达式进行 Erlang 模式匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1660655/