str_在公共Lisp中替换?

str_在公共Lisp中替换?,lisp,common-lisp,Lisp,Common Lisp,在公共Lisp中是否有类似于PHP的str_replace的函数 有一个名为cl ppcre的库: (cl-ppcre:regex-replace-all "qwer" "something to qwer" "replace") ; "something to replace" 通过安装。我认为标准中没有此类功能。如果不想使用正则表达式(cl ppcre),可以使用以下方法: (defun string-replace (search replace string &optional

在公共Lisp中是否有类似于PHP的str_replace的函数


有一个名为cl ppcre的库:

(cl-ppcre:regex-replace-all "qwer" "something to qwer" "replace")
; "something to replace"

通过安装。

我认为标准中没有此类功能。如果不想使用正则表达式(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))))
编辑:Shin Aoyama指出,用
“str\”ing“
”中的
“\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\/code>替换例如,
“str\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

(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)))

我特别喜欢使用输出为字符串的
,它通常比
串联

性能更好。如果替换仅为一个字符,通常情况下,您可以使用替换:

(substitute #\+ #\Space "a simple example") => "a+simple+example"

的副本?它应该在common lisp中,我不想安装任何其他库。我只有SLIME。如果你不想要elisp解决方案,你不应该用elisp标记问题。你说的lisp是什么意思?我从下面的评论中了解到,你指的是CL。你应该首先说。它应该在common lisp中,我不知道ant安装任何附加库。我只有SLIME。Common lisp不包括perl compatibe正则表达式,因为它们在几年后成为标准功能。您可以在此处找到替换字符串的简单实现:有用的注意:如果您计划用反斜杠替换某些文本,最好使用下面的答案。我已经尝试过了将其替换为cl ppcre,但这并不简单,因此实际上下面的函数更适合此作业。尽管后一个实现在部分为空字符串时挂起。它应该检查它,以确保正确。