emacs-devel
[Top][All Lists]
Advanced

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

Re: replace matches in any string


From: Ted Zlatanov
Subject: Re: replace matches in any string
Date: Thu, 02 Sep 2010 12:08:08 -0500
User-agent: Gnus/5.110011 (No Gnus v0.11) Emacs/24.0.50 (gnu/linux)

On Thu, 02 Sep 2010 18:21:22 +0200 Stefan Monnier <address@hidden> wrote: 

SM>    (let ((regex "\\(alpha\\)")
SM>          (string "gamma alpha beta"))
SM>      (when (string-match (concat "\\`.*?\\(?:" regex "\\).*\\'") string)
SM>        (replace-match "found greek letter \\1" nil nil string)))

SM> will do what you want, assuming your strings don't contain newlines, and
SM> assuming that providing `string' is not a problem.

SM> We could implement this feature efficiently by generalizing the `subexp'
SM> argument so that rather than subgroup-number it can also take a special
SM> new value `whole-string' which means "not just the whole matched text,
SM> but the whole freakin' string".  Then you could do:

SM>    (let ((regex "\\(alpha\\)")
SM>          (string "gamma alpha beta"))
SM>      (when (string-match regex string)
SM>        (replace-match "found greek letter \\1" nil nil string 
'whole-string)))

That would be great.  Then we wouldn't have to play the string-match
regex escaping game above.  But it complicates the code a bit to provide
`string'.  I think Lars's suggestion to always save `string' to the same
global variable is sensible; then we could say

 (replace-match "found greek letter \\1" nil nil 'whole-last-string)

to mean "replace in the whole freakin' string you last matched on" :)

In a few tests your example worked great.  Lars, WDYT?

In general, it would be really nice if there was a
match-string/string-match/replace-match API variation that worked like
Perl's $1...$9 and Perl's named captures.  Those simply contain the
matched substring.  Putting a name on the capture is especially nice in
recent Perls, so you can refer to the captured data symbolically without
the fragile index.  But that's not necessary for the feature I'm
requesting so put it on the wishlist...

SM> Of course, such string matching is a bit less optimized (and even less
SM> so if you replace "." with "\\(?:.\\|\n\\)" to handle newlines), so it
SM> might not be ideal.

I think it will be used in non-performance-critical pieces so it's OK.

Ted




reply via email to

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