Question

In reading the emacs help and emacs wiki I haven't found an obvious way to search for a regular expression and then simply delete all the matching text it finds. I originally thought I could use the regular expression search and replace feature M-x query-replace-regexp, but could not figure out how to replace my matches with an empty string. Hitting return on an empty string would simply exit. The field highlighted by the incremental reg expr search (C-M-s) doesn't obey the same rules as a marked block of text. Otherwise I would simply cut it (C-w).

Consider the following scenario. I wanted to strip the trailing zeros from a list of numbers that have 3 or more zeros.

0.075000
0.050000
0.10000
0.075000

So this is the round about way I solved it.

F3                - begin keyboard macro
C-M-s for 000*    - forward regexpr search
                    match the trailing zeros find the first match
C-<SPC>           - mark the position at the end of the match (after the last 0)
C-M-r for [1-9]   - reverse regexpr search
                    match the reverse non-zero digit, mark is now on the non-zero digit
C-f               - move mark forward one space
C-w               - cut/kill the text
F4                - end keyboard macro, run until list is processed

Surely there is a better way to do this. Any ideas?

Was it helpful?

Solution

use replace-regexp to do that. To strip trailing 0's from numbers that have 3 or more 0s:

M-x replace-regexp <RET>000+<RET><RET>

OTHER TIPS

Like replace-regexp?

M-x replace-regexp
Replace regexp: $.*foo
Replace regexp $.*foo with:

You can even make your own function, eg kill-regexp

In your scratch buffer (or some other buffer) write

(defun kill-regexp (regexp)
  (interactive "sRegular expression to kill: ")
  (replace-regexp regexp "")
)

Make sure the cursor is somewhere on the function and then evaluate the defun:

`M-x eval-defun`

(interactive ...) means you can call it interactively. Leading s means the regexp argument is a string. Text following it is what will be displayed at the prompt (minibuffer)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top