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

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

Re: How to replace-regexp by the average?


From: John Mastro
Subject: Re: How to replace-regexp by the average?
Date: Fri, 5 Jun 2015 14:12:47 -0700

<gnuist006@gmail.com> wrote:
> Given strings of this type
>
> TOKEN 123.456 12.3456 1234.56
>
> replace by
>
> TOKEN 67.9008 623.453
>
> where the first number is the average, ie what you get from the
> evaluation of
>
> (/ (+ 123.456 12.3456) 2.0)
>
> and second is also the average, ditto
>
> (/ (+ 1234.56 12.3456) 2.0)
>
> both upto 6 significant digits.
>
> I tried this but it does not work.
>
> (save-excursion (replace-regexp "TOKEN \\([0-9\\.]+\\) \\([0-9\\.]+\\) 
> \\([0-9\\.]+\\)" (concat "TOKEN (format "6.6f" (/ (+ \\1 \\2) 2.0)) (format 
> "6.6f" (/ (+ \\2 \\3) 2.0)) ) ))
>
> Any help in improving while keeping it readable one-liner sexp and
> maintaining the use of \\1 \\2 \\3 etc if possible ... ?

You can only use Lisp expressions in the replacement text for
`replace-regexp' in interactive calls (i.e. when used via `M-x' rather
than `M-:'). The syntax is also different from what you tried, for which
see `C-h f replace-regexp RET`.

Here's one stab at what it might look like in Lisp. This doesn't meet
all your requirements (it's not a one-liner and doesn't pay attention to
significant digits), and it's probably not the best way to do it, but
maybe it will give you some ideas.

    (defun replace-with-averages ()
      (interactive)
      (save-excursion
        (when (re-search-forward
               "TOKEN \\([0-9.]+\\) \\([0-9.]+\\) \\([0-9.]+\\)"
               nil t)
          (let ((i (string-to-number (match-string 1)))
                (j (string-to-number (match-string 2)))
                (k (string-to-number (match-string 3))))
            (replace-match (format "TOKEN %s %s"
                                   (/ (+ i j) 2.0)
                                   (/ (+ j k) 2.0)))))))

-- 
john



reply via email to

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