开发者

How to match a regexp with receive in Erlang?

There is the following block:

receive
... 
  {raw, Text} ->
      send(Socket, Text),
      master(State);
...
end.

I am wondering if it is possible to match a regexp in Text and have a simple c开发者_JAVA百科lause if the Text matches.


You can't do this directly in a pattern match (in this case a receive pattern) as there's no regular expression pattern. There is a regular expression library, so you can try the match after you receive the {text, Text} message, but it isn't the same as selectively receiving the message only if it matches a regular expression.

The one case you can do better than this is if your regular expression is a constant prefix of Text, like "^some prefix", where you can use the "some prefix" ++ _Var syntax:

receive
...
    {raw, Text = "some prefix" ++ _} ->
        send(Socket, Text),
        master(State);
...
end


You cannot use use regular expressions at all in patterns, at least not as regular expressions. Patterns have exactly the same structure as data constructors. This means that unless the regular expression is very simple and can be expressed as a pattern as in @archaelus example then there is no way to test the message without first removing it from the message queue. Then you can use the regular expression module to test the string and extract fields from it.

I don't see this changing in the foreseeable future.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜