按其部分搜索单词

时间:2014-09-26 18:04:36

标签: search lisp common-lisp

我必须编写一个程序,通过搜索给定的子字符串来搜索列表的所有“单词”。例如:(monday thursday friday) 搜索“ida” =星期五。

这样的事情:

(nth iday '(monday hello sup friday))

但它会标记错误。

3 个答案:

答案 0 :(得分:3)

你的表达毫无意义。 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)

答案 1 :(得分:1)

如果你只有一个连续的子串,可能有点矫枉过正。但是只要你想找到更复杂的匹配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)

答案 2 :(得分:0)

Common Lisp包含一个 find 函数,以及一个不区分大小写的 char-equal 函数,以及一个查找事件的函数 search 另一个序列中的序列。因此你可以这样做:

(find "iday" '(monday hello sup friday)
      :test (lambda (part whole)
              (search part whole :test 'char-equal))
      :key 'string)
;=> FRIDAY

:key 参数会应用于列表的每个元素,因此您获得"MONDAY""HELLO"等等,并且您正在搜索一个元素满足:test 功能。 :测试功能使用搜索在列表元素中查找"iday"的匹配项。 搜索字符等于)的:测试参数可确保对元素进行不区分大小写的比较。因此:

(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"
相关问题