6

在 Emacs 或 Vim 中,什么是连接字符串的平滑方式,如下例所示:

变换自:
    (阿尔法,贝塔,伽马)等等(123、456、789)
到:
    (阿尔法=123,贝塔=456,伽马=789)

它需要扩展到:

  • 其中许多行
  • 括号中的许多元素

我最近发现自己经常需要这种转变。

我在 Emacs 中使用 Evil,这就是为什么 Vim 答案可能也会有所帮助的原因。

更新:

解决方案并不像我希望的那样普遍。例如,当我有一个字符串列表并希望将它们分发到一个大型 XML 文档中时,我希望该解决方案也能正常工作。例如:

<item foo="" bar="barval1"/>
<item foo="" bar="barval2"/>
<item foo="" bar="barval3"/>
<item foo="" bar="barval4"/>

fooval1
fooval2
fooval3
fooval4

我制定了一个解决方案并将其添加为答案。

4

6 回答 6

2
%s/(\(\S\{-}\), \(\S\{-}\), \(\S\{-}\)).\{-}(\(\S\{-}\), \(\S\{-}\), \(\S\{-}\))/(\1=\4, \2=\5, \3=\6)

%s: 全局搜索和替换

\(\S{-}\),:非贪婪搜索直到下一个逗号的非空白字符,用“(”括起来以进行反向引用

\1=\4: 打印出第一个匹配,一个“=”符号,然后是第四个匹配

于 2012-12-19T23:55:57.533 回答
2

对于这样的文本转换,我会选择 awk:

这个单线可能会有所帮助:

awk -F'\\(|\\)' '{split($2,t,",");split($4,v,",");printf "( "; for(x in t)s=s""sprintf("%s=%s, ", t[x],v[x]);sub(", $","",s);printf s")\n";s=""}' file

小测试:

kent$  cat test
(alpha, beta, gamma) blah (123, 456, 789)
(a, b, c) foo (1, 2, 3)
(x, y, z, m, n) bar (100, 200, 300, 400, 500)

kent$  awk -F'\\(|\\)' '{split($2,t,",");split($4,v,",");printf "( "; for(x in t)s=s""sprintf("%s=%s, ", t[x],v[x]);sub(", $","",s);printf s")\n";s=""}' test

( alpha=123,  beta= 456,  gamma= 789)
( a=1,  b= 2,  c= 3)
(  m= 400,  n= 500, x=100,  y= 200,  z= 300)
于 2012-12-20T01:31:07.593 回答
1

这是一个 Vimscript 解决方案。它远没有 ash 的答案那么优雅,但它适用于任何长度的列表。

function! ListMerge()
    " Get line, remove text between lists, split lists at parentheses:
    let curline = getline('.')
    let curline = substitute(curline,')\zs.*\ze(','','g')
    let curline = substitute(curline,'(','','g')
    let lists = map(split(curline,')'),'split(v:val,",")')
    " Return if we don't have two lists of equal length:
    if len(lists) != 2 || len(lists[0]) != len(lists[1])
        return
    endif
    " Loop over the lists, remove whitespace, build the replacement string:
    let i=0
    let string = '('
    while i<len(lists[0])
        let string .= substitute(lists[0][i],'^ *','','')
        let string .= '='
        let string .= substitute(lists[1][i],'^ *','','')
        let string .= ', '
        let i+=1
    endwhile
    " Add the concluding bracket:
    let string = substitute(string,', $',')','')
    " Replace the current line with the string:
    execute "normal! S" . string
endfunction

然后,您可以在所有行上调用此函数,如下所示:

:%call ListMerge()
于 2012-12-20T00:05:26.597 回答
1

Emacs Lisp 版本的炖牛肉王子答案

(require 'cl)

(defun split-and-trim (str separator)
  (let ((strs (split-string str separator)))
    (mapcar (lambda (s)
              (replace-regexp-in-string "^\\s-+" "" s))
            (mapcar (lambda (s)
                      (replace-regexp-in-string "\\s-$" "" s)) strs))))

(defun my/merge-list (beg end)
  (interactive "r")
  (goto-char beg)
  (let ((endmark (set-mark end))
        (regexp "(\\([^)]+\\))[^(]+(\\([^)]+\\))"))
    (while (re-search-forward regexp end t)
      (let ((replace-start (match-beginning 0))
            (replace-end   (match-end 0))
            (keys-str (match-string-no-properties 1))
            (values-str (match-string-no-properties 2)))
        (let* ((keys (split-and-trim keys-str ","))
               (values (split-and-trim values-str ",")))
          (while (> (length keys) (length values))
            (setq values (append values '(""))))
          (let* ((pairs (mapcar* (lambda (k v)
                                   (format "%s=%s" k v)) keys values))
                 (transformed (format "(%s)" (mapconcat #'identity pairs ", "))))
            (goto-char replace-start)
            (delete-region replace-start replace-end)
            (insert transformed)))))
    (goto-char (marker-position endmark))))

例如,您选择区域如下

(alpha, beta, gamma)  blah (123, 456, 789)
(alpha, beta, gamma, delta)  blah (123, 456, 789, aaa)

在 Mx my/merge-list 之后

(alpha=123, beta=456, gamma=789)
(alpha=123, beta=456, gamma=789, delta=aaa)
于 2012-12-20T01:50:34.430 回答
1

我要描述的这种方法有点古怪,但它涉及到我能管理的最少的 Elisp 代码。仅当要加入的列表在删除逗号后可以解释为 Lisp 列表时才适用。如您的示例所示,字母字符的数字和序列会很好。

首先,确保加载了 Common Lisp 库: M-:(require 'cl)RET.

现在,从第一个列表开头的光标开始:

M-C-k ; 杀死前向性

C-e ; 行尾移动

M-C-b ; 后向性

M-C-k ; 杀死前向性

C-a ; 行首移动

C-k ; 杀线

现在blah(或其他)是 kill ring 中的第一个条目,第二个列表是第二个条目,第一个列表是第三个条目。

输入(,然后输入M-:( eval-expression),深呼吸,然后输入:

(loop with (a b) = (mapcar (lambda (x) (car (read-from-string (remove ?, x))))
                     (subseq kill-ring 1 3))
   for x in a for y in b do (insert (format "%s=%s, " y x)))

(出于演示目的,我已将其拆分,但您可以将其全部输入一行。)

然后最后DELDEL),你就完成了!如果你愿意,你可以把它变成一个宏。

于 2012-12-20T04:44:22.600 回答
0

我的方法是创建一个命令来设置匹配列表,然后使用 replace-regexp 作为第二个命令来分发匹配列表,利用 replace-regexp 现有的 \, 工具。

评估 Elisp,例如在 .emacs 文件中:

(defvar match-list nil
  "A list of matches, as set through the set-match-list and consumed by the cycle-match-list function. ")
(defvar match-list-iter nil
  "Iterator through the global match-list variable. ")
(defun reset-match-list-iter ()
  "Set match-list-iter to the beginning of match-list and return it. "
  (interactive)
  (setq match-list-iter match-list))
(defun make-match-list (match-regexp use-regexp beg end)
  "Set the match-list variable as described in the documentation for set-match-list. "
  ;; Starts at the beginning of region, searches forward and builds match-list.
  ;; For efficiency, matches are appended to the front of match-list and then reversed
  ;; at the end.
  ;;
  ;; Note that the behavior of re-search-backward is such that the same match-list
  ;; is not created by starting at the end of the region and searching backward.
  (let ((match-list nil))
    (save-excursion
      (goto-char beg)
      (while
          (let ((old-pos (point)) (new-pos (re-search-forward match-regexp end t)))
            (when (equal old-pos new-pos)
              (error "re-search-forward makes no progress.  old-pos=%s new-pos=%s end=%s match-regexp=%s"
                     old-pos new-pos end match-regexp))
            new-pos)
        (setq match-list
              (cons (replace-regexp-in-string match-regexp
                                              use-regexp
                                              (match-string 0)
                                              t)
                    match-list)))
      (setq match-list (nreverse match-list)))))
(defun set-match-list (match-regexp use-regexp beg end)
  "Set the match-list global variable to a list of regexp matches.  MATCH-REGEXP
is used to find matches in the region from BEG to END, and USE-REGEXP is the
regexp to place in the match-list variable.

For example, if the region contains the text: {alpha,beta,gamma}
and MATCH-REGEXP is: \\([a-z]+\\),
and USE-REGEXP is: \\1
then match-list will become the list of strings: (\"alpha\" \"beta\")"
  (interactive "sMatch regexp: \nsPlace in match-list: \nr")
  (setq match-list (make-match-list match-regexp use-regexp beg end))
  (reset-match-list-iter))
(defun cycle-match-list (&optional after-end-string)
  "Return the next element of match-list.

If AFTER-END-STRING is nil, cycle back to the beginning of match-list.
Else return AFTER-END-STRING once the end of match-list is reached."
  (let ((ret-elm (car match-list-iter)))
    (unless ret-elm
      (if after-end-string
          (setq ret-elm after-end-string)
        (reset-match-list-iter)
        (setq ret-elm (car match-list-iter))))
    (setq match-list-iter (cdr match-list-iter))
    ret-elm))
(defadvice replace-regexp (before my-advice-replace-regexp activate)
  "Advise replace-regexp to support match-list functionality. "
  (reset-match-list-iter))

然后解决原来的问题:

M-x set-match-list
Match regexp: \([0-9]+\)[,)]
Place in match-list: \1

M-x replace-regexp
Replace regexp: \([a-z]+\)\([,)]\)
Replace regexp with: \1=\,(cycle-match-list)\2

并解决 XML 示例:

[Select fooval strings.]
M-x set-match-list
Match regexp: .+
Place in match-list: \&

[Select XML tags.]
M-x replace-regexp
Replace regexp: foo=""
Replace regexp with: foo="\,(cycle-match-list)"
于 2012-12-26T21:26:43.570 回答