Common Lisp中是否有类似于PHP的str_replace函数的功能?
Common Lisp中是否有类似于PHP的str_replace函数的功能?
有一个名为cl-ppcre的库:
(cl-ppcre:regex-replace-all "qwer" "something to qwer" "replace")
; "something to replace"
通过quicklisp进行安装。
我认为标准库中没有这样的函数。如果不想使用正则表达式(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"
中将"\""
替换为"\\\""
的情况。因为我现在认为上面的方法相当繁琐,所以我应该提议在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)))
我特别喜欢使用with-output-to-string
,它通常比concatenate
表现更好。
(substitute #\+ #\Space "a simple example") => "a+simple+example"