我必須編寫一個程序,通過搜索給定的子字符串來搜索列表中的所有「單詞」。例如:(monday thursday friday)
搜索「ida」 =星期五。按其部分搜索單詞
事情是這樣的:
(nth iday '(monday hello sup friday))
,但會將標記錯誤。
我必須編寫一個程序,通過搜索給定的子字符串來搜索列表中的所有「單詞」。例如:(monday thursday friday)
搜索「ida」 =星期五。按其部分搜索單詞
事情是這樣的:
(nth iday '(monday hello sup friday))
,但會將標記錯誤。
你的表情毫無意義。 nth
用於按索引訪問元素。
您可以使用remove-if-not
從您的列表中只得到匹配的字符串:
(defun find-matching-substr (substr-sym list-of-symbols)
(remove-if-not (lambda (sym)
(search (string substr-sym)
(string sym)))
list-of-symbols))
CL-USER> (find-matching-substr 'day '(monday hello sup friday))
(MONDAY FRIDAY)
可能是有點矯枉過正,如果你只有一個連續的字符串。但是一旦你想找到更復雜的匹配cl-ppcre(正則表達式庫)想到。它可通過quicklisp獲得,並有詳細記錄。請注意,儘管將string
應用於符號將返回capital letters中的符號名稱。
(ql:quickload "cl-ppcre")
(defun find-matching-substr (regexp list-of-symbols)
(remove-if-not #'(lambda(sym)
(cl-ppcre:scan regexp (string sym)))
list-of-symbols))
;;looking for strings containing ida
(find-matching-substr "(i?)ida" '(monday tuesday thursday friday saturday))
(FRIDAY)
;;look for strings starting with f and ending in y
(find-matching-substr "(?i)f.*y" '(monday tuesday thursday friday saturday))
(FRIDAY)
;;look for strings containing exactly 3 vowels
(find-matching-substr "^([^AIEOU]*[AIEOU]){3}[^AIEOU]*$"
'(monday tuesday thursday
friday saturday sunday
anotherday dayafterantother))
(TUESDAY SATURDAY)
Common Lisp的包括找到功能,以及不區分大小寫的炭等於功能,以及功能搜索用於查找另一序列內的序列的發生。因此,你可以這樣做:
(find "iday" '(monday hello sup friday)
:test (lambda (part whole)
(search part whole :test 'char-equal))
:key 'string)
;=> FRIDAY
的:關鍵參數被應用到列表中的每個元素,讓您得到"MONDAY"
,"HELLO"
,等等,你正在尋找滿足一個元素:測試功能。 :測試函數使用搜索在列表元素中查找"iday"
的出現次數。 :測試自變量爲搜索(char-equal)確保元素不區分大小寫。因此:
(defun find-word (word words)
(find (string word) words
:test (lambda (part whole)
(search part whole :test 'char-equal))
:key 'string))
(find-word 'iday '(monday hello sup friday))
(find-word "idAY" '(monday hello sup friday))
;=> FRIDAY
(find-word "IDAY" '(monday hello sup "friday"))
(find-word 'iday '(monday hello sup "friday"))
;=> "friday"
'列表中的所有單詞...' - 我想OP要在列表中返回多個項目,以防萬一包含給定子字符串的多個符號,儘管仍然不完全清楚。 – Mark 2014-09-28 04:27:31
@Mark這是可能的,但標題不是「按部件搜索單詞」,例如「搜索Ida(...)=星期五」,而不是「搜索Ida」(...)=(星期五)」。 – 2014-09-28 10:27:52
嗨,歡迎SO。請顯示您的代碼和錯誤。在展示必要的信息之前,沒有人能夠告訴你的問題是什麼 – Deepend 2014-09-26 18:20:59
Stackoverflow不是人們做這樣的家庭作業的地方。顯示你的努力,你對你的問題可以解決的方式的想法。 – Mark 2014-09-27 08:01:43