Find and replace whole words (not substrings) in Emacs

1) In my setup process from my image editor to EMACS, I seem to have problems finding a clear way to make a relatively simple task for most editors: find and replace whole words (not substrings) in the text and find exact matches. Mx replace-string finds substrings as well as whole words. Is there a regex that does this?

2) Is there also a way to match exact strings? For example, if I wanted to replace myClaSs with an exact case for each letter, what should I do? Right now, the replace string matches myclass with myCLasS. As soon as I understood, only the first letters in this case match. I guess some regex will take care of this as well.

3) Is it possible to perform a wrapper search? Or I will always have to decide whether I am performing Cs (forward) or Cr (backward)

+6
source share
5 answers

Use anchor boundary bindings: \bfoo\b matches only foo , not foobar .

Then regular expressions are usually case sensitive. In most cases, you can explicitly make them case sensitive by adding (?I) or (?-i) to your regular expression. But I'm not sure if Emacs regexes can do this.

I do not know your third question. Unfortunately.

+7
source

All other answers provide information that you can use to get Emacs to do what you want. But you can also flip your own search / replace function to do what you want:

 (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 any key you want ...

+6
source

Firstly, can you ask a few questions to separate questions in the future? This makes it easier for others to help you and other users who have some of the same questions in the future to get help from past answers.

  • See @Tim answer

  • See Ch k M-% and read the match case section.

  • Executing Cs after the last match will tell you that you are at the end, pressing Cs will be completed again from the very beginning. Read the documents by pressing Ch i , then press * Emacs , then press g Repeat Isearch RET , from the second to the last paragraph.

+1
source

In question 2, if the search string is all lowercase, emacs does a default case search. You can force it to perform case-fold-search sensitive searches by setting case-fold-search to zero. You can put this in a .emacs: (setq case-fold-search nil) file.

+1
source

In question 1 (searching for whole words) \b in @Tim's answer cannot work when meeting with the _ character. It seems that foo\b might match foo_bar in Emacs (of course, it can't match Perl).

+1
source

Source: https://habr.com/ru/post/896908/


All Articles