2010-12-06 6 views
6

Lisp에서 PHP의 str_replace와 유사한 함수가 있습니까?Lisp의 str_replace?

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

quicklisp 통해 설치 : CL-ppcre라는 라이브러리가있다

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

+0

중복 된 http://stackoverflow.com/questions/90977/replace-char-in-emacs-lisp? – khachik

+1

그것은 공통적 인 lisp이어야하며 추가 라이브러리를 설치하고 싶지 않습니다. 방금 생리가있어. –

+0

elisp 솔루션을 원하지 않는다면 elisp로 질문을 태그하면 안됩니다. – sepp2k

답변

15

.

+0

그것은 공통적 인 lisp이어야하며 추가 라이브러리를 설치하고 싶지 않습니다. 방금 생리가있어. –

+0

Common Lisp에는 perl-compatibe 정규 표현식이 포함되어 있지 않습니다. replace-string의 간단한 구현은 다음에서 찾을 수 있습니다. http://cl-cookbook.sourceforge.net/strings.html#manip – koddo

+0

유용한 정보 : 일부 텍스트를 백 슬래시로 대체하려는 경우, 아래 답변. 나는 그것을 cl-ppcre로 바꾸려고 시도했으나 간단하지가 않아서 아래의 함수가이 작업에 더 적합했다. – MatthewRock

5

표준에는 그러한 기능이 없다고 생각합니다. 정규 표현식 (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)))) 

편집 : 신 아오야마는이에 "\\\""으로, 예를 들어, 교체하기위한 "\"" 작동하지 않는 것을 지적 "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))) 

나는 특히 일반적으로 concatenate보다 성능이 with-output-to-string의 사용 등이있다.

+0

* part *가 빈 문자열이면 후자의 구현이 중단됩니다. 올바른지 점검해야합니다. –