Short version: If i bound the scope of a search/replace to a region in the buffer (via the second/third optional argument of
search-forward and its derivates), how can i match the beginning of that region?
Longer version: Say, i have a test.txt which contains only
xxx yyy xxx xxx yyy xxx xxx yyy xxx xxx yyy xxx xxx yyy xxx xxx yyy xxx xxx yyy xxx xxx yyy xxx xxx yyy xxx xxx yyy xxx xxx yyy xxx xxx yyy xxx xxx yyy xxx xxx yyy xxx xxx yyy xxx
Now, I mark any part and like to run
M-x query-replace-regexp to replace the first three characters of the marked region. How can i achieve this with a regular expression? A naïve try would be to use
(defun test-1 (b e) (interactive "r") (query-replace-regexp "^..." "zzz" nil b e) )
^ matches only
bol (and so does
\` ), not the beginning of my region. In extension, i need a similar construction in a larger script that could be simplified to the following minimal example:
(defun test-2 () (interactive) (while (search-forward "xxx xxx" nil t) (let ((beg (match-beginning 0)) (end (match-end 0))) (query-replace-regexp "^xxx" "zzz" nil beg end) (goto-char (match-end 0)))))
Is there a way to match the beginning of any substring within a regionally bounded regular search?
I am aware that you could avoid the problem by working with
narrow-to-region and thus make the beginning of the region the sub-buffer's bol but i'd like to avoid this for the sake of context when I replace stuff in my documents.