如何替换一个模式的每个输出一次?

时间:2015-12-03 12:38:14

标签: regex vim vi

我想替换一个模式,我不知道确切的单词。我需要替换这些词的第一次出现。

输入: -

  

例如,这只是展示我的{need}的示例。这段{有}   没有意义,只是{an}例子。想象一下,我的{replace}应该完成   这段例如,这只是显示我的{need}的示例。   这段{没有意义,只是{an}例子。想象一下我的{替换}   应该在这段中完成。还有一些{text}

必需的输出: -

  

例如,这是显示Replace_Word的Replace_Word示例。这个   Replace_Word没有意义,只是{an}示例。想象一下Replace_Word   应该在这段中完成。例如,这只是{an}示例   显示我的{需要}。这段{没有意义,只是{an}例子。想像   我的{replace}应该在这段中完成。一些Replace_Word

示例模式s/\(\w*{\w*}\)/Replace_word/g

我是vim的初学者。我知道这是错的。我认为,需要使用for循环等

0,/Word_to_find/s/Word_to_find/Replace_word/g

2 个答案:

答案 0 :(得分:1)

源这个函数,然后在你的输入文件缓冲区中执行:

call ReplaceFirst('\S\+{[^}]*}',"REPLACE_WORD")

它应该做你想要的:

function! ReplaceFirst(pat, rep) 
    let end = line('$')
    let pat_dict = {}
    for i in range(1,end)
        let line = getline(i)
        while 1
            let found = matchstr(line, a:pat)
            if found == ""
                break
            endif
            let pat_dict[found] = 0
            let line = substitute(line, a:pat, '','1')
        endwhile
    endfor
    "do replacement 
    for  k in keys(pat_dict)
        execute 'normal! gg'
        execute '/\V'.k
        execute 's/\V'.k.'/'.a:rep.'/'
    endfor
endfunction

在这里测试:

enter image description here

请注意,此函数不是那么通用,如果您的模式包含/,则该函数可能会失败。至少它显示了我的想法。对于这些增强功能,您可以完成它。

答案 1 :(得分:1)

以下是诀窍,但确实可以改进:

function! ReplaceFirst(line1, line2, pattern, replace)
    let words = []  " To store all possible patterns
    for i in range(a:line1, a:line2)  " Loop over lines in the desired range
        let line = getline(i)
        let c = 1  " Counter for multiple matches in the same line
        while 1  " For each match in the same line:
            let s = matchstr(line, a:pattern, 0, c)
            if s == ""
                break
            endif
            if index(words, s) == -1  " If this match was not already stored:
                call add(words, s)  " Add this match
            endif
            let c = c + 1  " Go to next match in the same line
        endw
    endfor

    for word in words  " For all found matches:
        call cursor(a:line1, 1)  " Go to the beginning of range,
        call search('\V'.word, 'c')  " Then to the first occurence of the match
        " Replace the first occurence in the line:
        exe 's/\V'.word."/".a:replace
    endfor
endf

" Command that takes two args: first one is the pattern, second one is the 
" replace word:
command! -range -nargs=* ReplaceFirst call ReplaceFirst(<line1>, <line2>, <f-args>)

" Example:
" :%ReplaceFirst \<\w*{\w*} REPLACE_WORD