henrique-marcomini-m

henrique-marcomini-m

How to pattern match (or guards) if a string is alphanumeric

I have the following code:


defp has_char_in_string?(value), do: Regex.match?(~r/[^\d]/, value)

def somefun(arg) do
  
  case has_char_in_string?(arg) do
    true -> foo()
    false -> bar()
  end

end

And I really want to keep this regex within this module and do not externalize this logic. But I also want to use pattern matching or guards instead of a case. Is this even possible? And if it is, how?

Thanks in advance

Most Liked

peerreynders

peerreynders

Probably not what you are looking for:

def somefun(true),
  do: foo()

def somefun(false),
  do: bar()

def somefun(arg) when is_binary(arg),
  do: Regex.match?(~r/[^\d]/, arg)
      |> somefun()

or

defp p_somefun(true),
  do: foo()

defp p_somefun(false),
  do: bar()

def somefun(arg) when is_binary(arg) do
  Regex.match?(~r/[^\d]/, arg)
  |> p_somefun()
end
al2o3cr

al2o3cr

It’s possible, especially if the regular expression is simple - you can translate the regex into its corresponding finite state machine and represent that with pattern matching:

defmodule RegexRecursion do
  def somefun(arg) do
    call_bar(arg)
  end

  defp call_bar("0" <> rest), do: call_bar(rest)
  defp call_bar("1" <> rest), do: call_bar(rest)
  defp call_bar("2" <> rest), do: call_bar(rest)
  defp call_bar("3" <> rest), do: call_bar(rest)
  defp call_bar("4" <> rest), do: call_bar(rest)
  defp call_bar("5" <> rest), do: call_bar(rest)
  defp call_bar("6" <> rest), do: call_bar(rest)
  defp call_bar("7" <> rest), do: call_bar(rest)
  defp call_bar("8" <> rest), do: call_bar(rest)
  defp call_bar("9" <> rest), do: call_bar(rest)

  defp call_bar(""), do: bar()
  defp call_bar(x) when is_binary(x), do: foo()

  defp foo(), do: IO.puts("foo")
  defp bar(), do: IO.puts("bar")
end

Here, the regex [^\d] translates to a state machine that stays in call_bar as long as each character is 0-9, actually calls bar given an empty string, and calls foo otherwise.

If the regex doesn’t involve backreferences or lookaheads (so it’s a theory-of-languages regular expression), it’s always possible to do this.

HOWEVER

The example above is a good example of how this approach obfuscates what should have been code like this:

defmodule RegexRecursionSimple do
  def somefun(arg) when is_binary(arg) do
    if Regex.match?(~r/[^\d]/, arg) do
      foo()
    else
      bar()
    end
  end

  defp foo(), do: IO.puts("foo")
  defp bar(), do: IO.puts("bar")
end

I’m very curious what’s motivating the preference for pattern matching here; it’s not the right tool for the job.

hauleth

hauleth

TBH I would say that Regex is overkill there. And your pattern match can be improved:

def somefun(<<num>> <> rest) when num in ?0..?9, do: call_bar(rest)
def somefun(""), do: bar()
def somefun(bin) when is_binary(bin), do: foo()

The problem with regular expressions the use backtracking engine (and PCRE is such engine) is that it can explode to O(n^2) with some expressions (namely nested wildcard matches). And such cases have been spotted on the wild with pretty simple expressions.

NobbZ

NobbZ

No, there is no way to make this regex or even something semantically equivalent into a guardsave predicate.

kip

kip

ex_cldr Core Team

I have a package called ex_cldr_unicode that includes guards for

These all operate on the Unicode character classes so it covers what passes for a digit in a more complete sense. It might help or give you some ideas.

Note that it works on code points since there is a limited set of underlying functions that can be used in guards.

There is another bunch of functions that might be helpful, including Cldr.Unicode.alphanumeric?/1 which will return a boolean and also uses the full Unicode definitions (not just Latin1):

iex> Cldr.Unicode.alphanumeric? "1st"
true

iex> Cldr.Unicode.alphanumeric? "KeyserSöze1995"
true

iex> Cldr.Unicode.alphanumeric? "3段"                 
true

Where Next?

Popular in Questions Top

jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod -- where is this set? Thanks.
New
sergio
In Ruby, I can go: User.find_by(email: "foobar@email.com").update(email: "hello@email.com") How can I do something similar in Elixir? ...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
lk-geimfari
What is most correct way to open, read and parse JSON file with poison? For example if we have example.json file in root of some projec...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
LegitStack
I’m trying to make a websocket server in Phoenix or raw Elixir. I heard about gun, I think I could use cowboy, but since I’m not that sma...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID&lt;0.412.0&gt; terminating ** (Postgrex.Error) FATAL...
New

Other popular topics Top

lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New
Jim
As a follow up to my earlier question: I have the code compiling and running but not getting a successful login from the rest server. ...
New
chrismccord
As promised, the first release candidate of Phoenix 1.3.0 is out! This release focuses on code generators with improved project structure...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
johnnyicon
Hi all, I've just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I'm trying to use Postg...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New

We're in Beta

About us Mission Statement