kod*_*ddo 17

有一个名为cl-ppcre的库:

(cl-ppcre:regex-replace-all "qwer" "something to qwer" "replace")
; "something to replace"
Run Code Online (Sandbox Code Playgroud)

通过quicklisp安装它.


Sva*_*nte 6

我认为标准中没有这样的功能.如果您不想使用正则表达式(cl-ppcre),可以使用:

(defun string-replace (search replace string &optional count)
  (loop for start = (search search (or result string)
                            :start2 (if start (1+ start) 0))
        while (and start
                   (or (null count) (> count 0)))
        for result = (concatenate 'string
                                  (subseq (or result string) 0 start)
                                  replace
                                  (subseq (or result string)
                                          (+ start (length search))))
        do (when count (decf count))
        finally (return-from string-replace (or result string))))
Run Code Online (Sandbox Code Playgroud)

编辑: Shin Aoyama指出,这不适用于替换,例如, "\"""\\\""in "str\"ing".由于我现在认为上述内容相当繁琐,我应该提出Common Lisp Cookbook中给出的实现,这要好得多:

(defun replace-all (string part replacement &key (test #'char=))
  "Returns a new string in which all the occurences of the part 
is replaced with replacement."
  (with-output-to-string (out)
    (loop with part-length = (length part)
          for old-pos = 0 then (+ pos part-length)
          for pos = (search part string
                            :start2 old-pos
                            :test test)
          do (write-string string out
                           :start old-pos
                           :end (or pos (length string)))
          when pos do (write-string replacement out)
          while pos)))
Run Code Online (Sandbox Code Playgroud)

我特别喜欢使用with-output-to-string,它通常表现得比concatenate.


Leo*_*Leo 5

如果替换只有一个字符,这是经常的情况,你可以使用替换:

(substitute #\+ #\Space "a simple example") => "a+simple+example"
Run Code Online (Sandbox Code Playgroud)