string 检查字符串是否包含 clojure 中的子字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26386766/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if String contains substring in clojure
提问by Luke
I need to check if a java String contains a substring in my tests.
我需要检查 java String 在我的测试中是否包含子字符串。
This doesn't work because java strings are not collections:
这不起作用,因为 java 字符串不是集合:
(deftest test_8
(testing "get page from sputnik"
(let [
band "Isis"
page (get-sputnikpage-for-artist band)
]
(is (contains? band "Isis")))));does NOT work
Is there a way to convert java strings into collections? Or can I check for substring occurences in other ways?
有没有办法将java字符串转换为集合?或者我可以通过其他方式检查子字符串的出现吗?
回答by Diego Basch
The easiest way is to use the contains
method from java.lang.String
:
最简单的方法是使用以下contains
方法java.lang.String
:
(.contains "The Band Named Isis" "Isis")
(.contains "The Band Named Isis" "Isis")
=> true
=> 真
You can also do it with regular expressions, e.g.
你也可以用正则表达式来做,例如
(re-find #"Isis" "The Band Named Isis")
=> "Isis"
=>“伊希斯”
(re-find #"Osiris" "The Band Named Isis")
=> nil
=> 零
If you need your result to be true or false, you can wrap it in boolean
:
如果您需要结果为真或假,您可以将其包装在boolean
:
(boolean (re-find #"Osiris" "The Band Named Isis"))
(boolean (re-find #"Osiris" "The Band Named Isis"))
=> false
=> 假
回答by Sanghyun Lee
Clojure 1.8has introduced includes?function.
Clojure 1.8已经引入了includes?功能。
(use '[clojure.string :as s])
(s/includes? "abc" "ab") ; true
(s/includes? "abc" "cd") ; false
回答by Thumbnail
Strings are seqable:
字符串是可排序的:
(seq "Hello") ;;=> (\H \e \l \l \o)
... so you coulduse the sequence library to find a match:
...因此您可以使用序列库来查找匹配项:
(defn subsumes [main sub]
(some
(partial = (seq sub))
(partition (count sub) 1 main)))
(subsumes "Hello" "ll") ;;=>> true
... but it's simpler and much faster to do as Diego Basch suggested.
...但正如 Diego Basch 建议的那样,它更简单、更快捷。