Clojure / ClojureScript中的一个不区分大小写的过滤器 [英] A case-insensitive filter in Clojure / ClojureScript

查看:184
本文介绍了Clojure / ClojureScript中的一个不区分大小写的过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个功能:

(defn list-data [alist filter-text]
 (filter (fn [x] (if (nil? filter-text) true
                     (> (.indexOf x filter-text) -1))) alist))

(list-data ["Lion" "Zebra" "Buffalo" "Antelope"] "a")
;=> ("Zebra" "Buffalo")

是否有更加惯用的方式写这个函数,事实上,我不想要一个区分大小写的过滤器,意味着我想要(list-data [LionZebraBuffaloAntelope]a)返回以下内容:

Is there a more idiomatic way of writing this function and respect the fact that I don't want a case-sensitive filter, meaning I would like that (list-data ["Lion" "Zebra" "Buffalo" "Antelope"] "a")returns the following:

;=> ("Zebra" "Buffalo" "Antelope")

谢谢!

(这将需要在 .cljs 文件中工作)

(This would need to work in a .cljs file)

推荐答案

在Clojure本身,你通常会使用正则表达式。在Java正则表达式中,您可以通过在要进行匹配的情况下提供不区分大小写的标志,或者在全局不区分大小写的正则表达式开始时执行此操作:

In Clojure itself you would normally do this with a regular expression. In Java regular expressions you can do this by giving in a flag for case-insensitivity for the match you want to make, or at the start of the regex for global case-insensitivity:

  (filter #(re-find #"(?i)a" %)
          ["Lion" "Zebra" "Buffalo" "Antelope"])

纯JavaScript正则表达式只支持全局标志。它们作为第二个参数以字符串形式提供给正则表达式构造函数:

Pure Javascript regular expressions only support global flags. They are given in as string as the second parameter to the regex constructor:

  (filter #(re-find (js/RegExp. "a" "i") %)
          ["Lion" "Zebra" "Buffalo" "Antelope"])

$ b $但是,为了方便起见,为了保持Java和Javascript之间的正则表达式类似,Clojurescript阅读器将全局java样式标志(正则表达式开头的那些)转换为它们的JavaScript全局等同体。

However, as convenience and to keep the regexes between Java and Javascript similar, the Clojurescript reader translates global java style flags (those at the start of the regex) to their Javascript global equivalent.

所以第一个例子也适用于Clojurescript。请注意,非全局标志将不能在Clojurescript中工作在Clojure中。

So the first example works in Clojurescript as well. Be aware though that non-global flags won't work in Clojurescript where they would work in Clojure.

这篇关于Clojure / ClojureScript中的一个不区分大小写的过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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