Find and Replace Whole Words (not substrings) in Emacs
1) In my process of adjusting from my GUI editor to EMACS I seem to have trouble finding a clear-cut way to do a relatively simple task for most editors: Find and replace whole words (non-substrings) within a text and find exact matches. M-x replace-string finds substrings as well as whole words. Is there a regexp that does this?
2) Also, is there a way to match exact strings? For example if I wanted to replace myClaSs with the exact case for each letter what would I have to do? Right now the replace-string m开发者_JAVA百科atches myclass with myCLasS. As I udnerstand only the first letters in the case are matched. I'm assuming some regexp takes care of this also.
3) Is there an option to do a wrap-around search? Or will I always have to decide whether I do C-s (forward) or C-r (backward)
Use word boundary anchors: \bfoo\b
only matches foo
, not foobar
.
Then, regular expressions usually are case-sensitive. In most flavors, you can explicitly make them case-sensitive by prepending (?I)
or (?-i)
to your regex. But I'm not sure if Emacs regexes can do that.
I have no idea about your third question. Sorry.
All the other answers provide information you can use to get Emacs to do what you want. But you can also roll your own search/replace function to do what you want like so:
(defun search-replace-ala-octi (tosearch toreplace)
(interactive "sSearch for word: \nsReplace with: ")
(save-excursion
(goto-char (point-min))
(let ((case-fold-search nil)
(count 0))
(while (re-search-forward (concat "\\b" tosearch "\\b") nil t)
(setq count (1+ count))
(replace-match toreplace 'fixedcase 'literal))
(message "Replaced %s match(es)" count))))
And bind it to whatever key you want...
Firstly, can you please put multiple questions into separate questions in the future? It makes it easier for others to help you and for other users who have some of the same questions in the future to get help from past answers.
See @Tim's answer
See
C-h k M-%
and read the section about case matchingDoing
C-s
after the last match will prompt you that you're at the end, hittingC-s
again will wrap from the beginning. Read the docs by hittingC-h i
then click on* Emacs
then hitg Repeat Isearch RET
, second to last paragraph.
For question 2, if the search string is all lower-case, emacs does a case-insensitive search by default. You can force it to do a case-sensitive search by setting case-fold-search
to nil. You can put this in your .emacs file: (setq case-fold-search nil)
.
On question 1 (whole word search)
\b
in @Tim 's answer cannot work when meeting the character _
. It seems that foo\b
can match foo_bar
in Emacs (of course it cannot match in Perl).
精彩评论