[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: string-replace question -- changing names like variable_name to var
Re: string-replace question -- changing names like variable_name to variableName
Tue, 03 Sep 2002 15:39:40 +0100
Gnus/5.090007 (Oort Gnus v0.07) Emacs/21.2.90 (i386-mingw-windows98.2222)
[...] variable_name --> variableName
> Is there an easier way to do this short of some lisp like:
> (replace-string "_a" "A")
> (replace-string "_A" "A")
> (replace-string "_b" "B")
Why yes there is. Using a small amount of knowledge of regexps,
and a few other Emacs functions.
Note firstly, that the docstring of replace-string explicitly
recommends against its use in lisp programs:
/----[ C-h f replace-string RET ]
| This function is usually the wrong thing to use in a Lisp program.
| What you probably want is a loop like this:
| (while (search-forward FROM-STRING nil t)
| (replace-match TO-STRING nil t))
| which will run faster and will not set the mark or print anything.
However, neither replace-string nor search-forward allow the use
of regexps in their syntax, hence, we need to use the regexp
equivalents, namely re-search-forward
Using these bits of information, we come up with
(let ((case-fold-search nil)) ; make sure we don't ignore
; case in our search, if this
; isn't a problem, then change
; the nil on this line to t.
(while (re-search-forward ; search forward for a regular
"\\([a-z]\\)_\\([a-z]\\)" ; this regexp matches
; something of the form:
; foo_bar, but not _bar, or
; foo_. If you want to match
; capitalised letters add A-Z
; to the character
; groupings. Or change the
; binding of case-fold-search
; to t.
nil ; no bound on the search
t) ; don't error if the match is
; not found.
(replace-match ; replace the matched text with:
(concat (match-string 1) ; a concatenation of the 1st
; \\(..\\) grouping. and...
(upcase ; the uppercase equivalent of:
(match-string 2))) ; the 2nd \\(..\\) grouping.
t))) ; since we've gone to all the
; trouble of changing the
; case, treat our string as FIXEDCASE
I hope the comments are suitably explanatory.
lawrence mitchell <address@hidden>