Clojure正则表达式:如果字符串是URL,则返回字符串 [英] Clojure Regex: If string is a URL, return string

查看:132
本文介绍了Clojure正则表达式:如果字符串是URL,则返回字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Clojure中给定字符串,返回有效的URL。

How can I return a valid URL given a string in Clojure.

 (re-matches #"????" "www.example.com"))
 (re-matches #"????" "http://example.com"))
 (re-matches #"????" "http://example.org")) // returns "http://example.org"
 (re-matches #"????" "htasdtp:/something")) // returns nil


推荐答案

验证URL并不简单。也许用正则表达式验证太复杂了。幸运的是,有一个名为 Apache Commons 的库,其中包含 UrlValidator

Validating URL is not simple. Perhaps it's too complex to validate with regexp. Fortunately, there's a library called Apache Commons, which contains UrlValidator.

由于Clojure可以使用Java库,因此您可以使用Apache Commons的UrlValidator来验证程序中的URL。

Since Clojure can use Java library, you can use Apache Commons' UrlValidator to validate URL in your program.

首先,在 project.clj 中添加依赖项。在依赖向量中添加以下行。

First, add dependency in your project.clj. Add the following line in your dependency vector.

[commons-validator "1.4.1"]

然后,您可以定义函数 valid-url?布尔值。

And then, you can define a function, valid-url? which returns boolean.

(import 'org.apache.commons.validator.UrlValidator)

(defn valid-url? [url-str]
  (let [validator (UrlValidator.)]
    (.isValid validator url-str)))

现在,您可以使用此功能执行所需的操作。或者,您可以修改上述函数,以在参数为有效URL时返回URL字符串。

Now, you can do what you want with this function. Or you can modify the above function to return the URL string when it's argument is valid URL.

这篇关于Clojure正则表达式:如果字符串是URL,则返回字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆