我必须编写一个程序,通过搜索给定的子字符串来搜索列表中的所有“单词”。例如:(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