2010-12-06 6 views
6

LispのPHPのstr_replaceに似た関数がありますか?Lispのstr_replaceですか?

http://php.net/manual/en/function.str-replace.php

+0

重複したhttp://stackoverflow.com/questions/90977/replace-char-in-emacs-lisp? – khachik

+1

これは普通のlispでなければならないので、私は追加のライブラリをインストールしたくありません。私はSLIMEを持っているだけです。 –

+0

elispソリューションが必要ない場合は、elispで質問にタグを付けるべきではありません。 – sepp2k

答えて

15

CL-ppcreと呼ばれるライブラリがあります:

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

quicklispを経由して、それをインストールします。

+0

これは普通のlispでなければならないので、私は追加のライブラリをインストールしたくありません。私はSLIMEを持っているだけです。 –

+0

Common Lispはperl-compatibe正規表現を含んでいません。ここでreplace-stringの簡単な実装を見つけることができます:http://cl-cookbook.sourceforge.net/strings.html#manip – koddo

+0

便利なメモ:テキストをバックスラッシュに置き換える予定がある場合は、以下の答え。私はcl-ppcreで置き換えようとしましたが、それは簡単ではないので、実際には以下の関数がこの仕事に適していました。 – MatthewRock

5

このような機能は標準ではないと思います。

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

はEDIT:新青山はこれがで"\\\""で、例えば、"\""を交換するために動作しないことを指摘し、あなたが正規表現(CL-ppcre)を使用したくない場合は、これを使用することができます"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))) 

I特に一般concatenateより良好に機能with-output-to-stringの使用、などが挙げられます。

+0

* part *が空文字列の場合、後者の実装はハングアップしますが。正しいことを確認する必要があります。 –