如何在代码中同时交换或替换多个字符串?

前端之家收集整理的这篇文章主要介绍了如何在代码中同时交换或替换多个字符串?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
给出以下代码示例:
  1. uint8_t i,in,ni;
  2. i = in = 2; ni = 1;
  3. while (2 == i > ni) in++;

如何使用emacs,vi,* nix命令或其他任何东西分别用in,ni和i或inni,inin和nini替换i,in和ni?

如果我没有弄错的话,到目前为止提供的解决方案(使用Perl和Vim)在任何替换都是要替换的后一个词中时不能正常工作.特别是,没有一个解决方案适用于第一个例子:“i”将被替换为“in”,然后将被错误地替换为“ni”,然后通过后续规则返回“i”,而它应该保留作为“在”.

替换不能独立承担并连续应用;它们应该并行应用.

在Emacs中,您可以这样做:

M-xparallel更换,

并在提示符下输入

我在ni ni ni.

替换将发生在光标和缓冲区的末尾之间,或者在一个区域中(如果选择了一个).

(如果你在〜/ .emacs.d / init.el中有这个定义:-)

  1. (require 'cl)
  2. (defun parallel-replace (plist &optional start end)
  3. (interactive
  4. `(,(loop with input = (read-from-minibuffer "Replace: ")
  5. with limit = (length input)
  6. for (item . index) = (read-from-string input 0)
  7. then (read-from-string input index)
  8. collect (prin1-to-string item t) until (<= limit index)),@(if (use-region-p) `(,(region-beginning),(region-end)))))
  9. (let* ((alist (loop for (key val . tail) on plist by #'cddr
  10. collect (cons key val)))
  11. (matcher (regexp-opt (mapcar #'car alist) 'words)))
  12. (save-excursion
  13. (goto-char (or start (point)))
  14. (while (re-search-forward matcher (or end (point-max)) t)
  15. (replace-match (cdr (assoc-string (match-string 0) alist)))))))

编辑(二零一三年八月二十零日):

一些增强功能

>对于只给出两个项目的特殊情况,改为执行交换(即相互替换);
>以与查询替换相同的方式要求确认每次更换.

  1. (require 'cl)
  2. (defun parallel-query-replace (plist &optional delimited start end)
  3. "Replace every occurrence of the (2n)th token of PLIST in
  4. buffer with the (2n+1)th token; if only two tokens are provided,replace them with each other (ie,swap them).
  5.  
  6. If optional second argument DELIMITED is nil,match words
  7. according to Syntax-table; otherwise match symbols.
  8.  
  9. When called interactively,PLIST is input as space separated
  10. tokens,and DELIMITED as prefix arg."
  11. (interactive
  12. `(,(loop with input = (read-from-minibuffer "Replace: ")
  13. with limit = (length input)
  14. for j = 0 then i
  15. for (item . i) = (read-from-string input j)
  16. collect (prin1-to-string item t) until (<= limit i)),current-prefix-arg,(region-end)))))
  17. (let* ((alist (cond ((= (length plist) 2) (list plist (reverse plist)))
  18. ((loop for (key val . tail) on plist by #'cddr
  19. collect (list (prin1-to-string key t) val)))))
  20. (matcher (regexp-opt (mapcar #'car alist)
  21. (if delimited 'words 'symbols)))
  22. (to-spec `(replace-eval-replacement replace-quote
  23. (cadr (assoc-string (match-string 0) ',alist
  24. case-fold-search)))))
  25. (query-replace-regexp matcher to-spec nil start end)))

猜你在找的Bash相关文章