【问题标题】:Elixir: How to count urls in a stringElixir:如何计算字符串中的 url
【发布时间】:2020-07-07 11:15:02
【问题描述】:

假设我有一个字符串:

content = "Please visit https://www.google.com...\nOr visit http://my.website.io\nhttp://myfriends.website.com\nOr https://www.myneigborsite.com, http://visit.me.com"

字符串中有5个url。

如何使用语法计算 url?

我尝试过使用Regex.scan/2 |> Enum.count/1String.split/2 |> Enum.count/1

我也尝试了我在互联网上找到的每个 http/https 正则表达式,但我仍然无法获得正确的输出。

这是我试过的一个。

iex> content
...> |> String.split(~r/^(https?):\/\/[^\s$.?#].[^\s]*$/)
...> |> Enum.count()
...> |> Kernel.-(1)
-1

另一个具有相同正则表达式的..

iex> Regex.scan(~r/^(https?):\/\/[^\s$.?#].[^\s]*$/, content) |> Enum.count()
0

但是当我检查正则表达式是否匹配某些网址时

iex> Regex.match?(~r/^(https?):\/\/[^\s$.?#].[^\s]*$/, "https://www.google.com")
true
iex(48)> Regex.match?(~r/^(https?):\/\/[^\s$.?#].[^\s]*$/, "http://my.website.io")
true

确实匹配。 我不知道有什么问题。请帮帮我。

【问题讨论】:

    标签: regex string count elixir


    【解决方案1】:

    您只需要 count 个 url,这意味着您不需要过于复杂的正则表达式。

    ~r|https?://[\w.-]+|
    |> Regex.scan(content)
    |> Enum.count()
    #⇒ 5
    

    您的尝试失败了,因为您在表达式中添加了 EOL 匹配器 $,当 URL 未终止字符串时,显然不匹配。

    【讨论】:

    • 哇,答案很快!感谢您指出正则表达式中的$
    猜你喜欢
    • 1970-01-01
    • 2022-12-21
    • 2011-04-29
    • 1970-01-01
    • 2019-12-28
    • 1970-01-01
    相关资源
    最近更新 更多