正则表达式 – 如何使用正则表达式进行Erlang模式匹配?

栏目: Erlang · 发布时间: 5年前

内容简介:翻译自:https://stackoverflow.com/questions/1660655/how-to-do-erlang-pattern-matching-using-regular-expressions

当我编写用于文本解析的Erlang程序时,我经常遇到我希望使用正则表达式进行模式匹配的情况.

例如,我希望我可以做这样的事情,其中​​〜是一个“组合”的正则表达式匹配运算符:

my_function(String ~ ["^[A-Za-z]+[A-Za-z0-9]*$"]) ->
    ....

我知道正则表达式模块(重新),但AFAIK你不能在模式匹配或守卫时调用函数.

此外,我希望匹配字符串可以以不区分大小写的方式完成.这很方便,例如,在解析HTTP标头时,我很乐意做这样的事情,其中​​“Str~ {Pattern,Options}”的意思是“使用选项选项匹配模式模式”:

handle_accept_language_header(Header ~ {"Accept-Language", [case_insensitive]}) ->
    ...

两个问题:

>你通常只使用标准的Erlang来处理这个问题?是否有一些机制/编码风格在简洁和易于阅读方面接近于此?

> Erlang有没有工作(EEP?)来解决这个问题?

除了提前运行正则表达式然后对结果进行模式匹配之外,你真的没有太多选择.这是一个非常简单的例子,它接近我认为你所追求的,但它确实遭受了重复两次regexp所需的缺陷.通过使用宏在一个位置定义每个正则表达式,可以减少痛苦.
-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]).

翻译自:https://stackoverflow.com/questions/1660655/how-to-do-erlang-pattern-matching-using-regular-expressions


以上所述就是小编给大家介绍的《正则表达式 – 如何使用正则表达式进行Erlang模式匹配?》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Introduction to the Design and Analysis of Algorithms

Introduction to the Design and Analysis of Algorithms

Anany Levitin / Addison Wesley / 2006-2-24 / USD 122.00

Based on a Based on a new classification of algorithm design techniques and a clear delineation of analysis methods, "Introduction to the Design and Analysis of Algorithms" presents the subject in a c......一起来看看 《Introduction to the Design and Analysis of Algorithms》 这本书的介绍吧!

在线进制转换器
在线进制转换器

各进制数互转换器

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具