help-gnu-emacs
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: I can't believe: replace regexp in a string


From: Klaus Berndl
Subject: Re: I can't believe: replace regexp in a string
Date: 14 Feb 2003 10:04:08 +0100
User-agent: Gnus/5.09 (Gnus v5.9.0) Emacs/21.2

On 14 Feb 2003, Stefan Kamphausen wrote:

>  Dear elispWizards,
>  
>  somehow I can't believe it. When I try to replace a regexp in a string
>  I have to create a temporary buffer and use the usual buffer
>  replacement commands or write a loop over the sequence. Is that true?
>  I have found a posting in this group describing that and have looked
>  at the XEmacs sources of subr.el where a defun replace-in-string is
>  defined which does one of the above procedures depending on the length
>  of the string. Having coded in Perl a good deal this seems quite
>  strange to me, but if it is the elispish way to do it, I'll give in
> :-)

There is no need to believe this because elisp can also replace regexps in
strings - even without temp. buffers.

In general a combination of string-match and replace-match does the trick, see
the doc-strings; both of them can get a STRING argument.

For replacing all occurences of a regexp in a string a while loop with
string-match (the condition) and replace-match (the body) is sufficient.

I have already written a function:

(defun re-replace-all-string (regexp replacement string
                                     &optional regreg start end fixedcase
                                     literal subexp)
"Replaces in STRING REGEXP with REPLACEMENT between START and END
\(or - if not nil - within the substring specified by REGREG) and returns
a list containing:
1) the new string
2) the start (usefull if substring is defined by REGREG)
3) the - possible - new END
4) the number of replacements made.
Returns nil if STRING is nil.
For START and END nil means begin of string (end of string).
For the arguments REPLACEMENT, FIXEDCASE, LITERAL and SUBEXP look
at `replace-match' with one extension: If REPLACEMENT is exactly
`<any single char>*' then the matching is overwritten with a string of
same length consisting of <any single char>. If REPLACEMENT is exactly
`<any single char>\\*' then the REPLACEMANT will be interpreted as really
'`<any single char>*', i.e. a character followed by a star. This extension
is only active if LITERAL is nil!"
 ;; here comes the code
 )

If you want i can post it...

Ciao,
Klaus

-- 
Klaus Berndl                    mailto: klaus.berndl@sdm.de
sd&m AG                         http://www.sdm.de
software design & management    
Thomas-Dehler-Str. 27, 81737 München, Germany
Tel +49 89 63812-392, Fax -220


reply via email to

[Prev in Thread] Current Thread [Next in Thread]