2017-02-15 82 views
0

我需要查找具有相同模式的所有字符串對。 例如:VIM:刪除具有相同模式的字符串

another string, that is not interesting 
la-di-da-di __pattern__ -di-la-di-la 
la-di-da-da-di-la __pattern__ -la-da-li-la 
and yet another usual string 

所以我想__pattern__內刪除字符串。

我不知道如何做到這與內建命令做到這一點,我現在具備的功能,這並不正常工作:

function! DelDup(pattern) 
    echom a:pattern 
    redir => l:count 
    execute "normal! :%s/a:pattern//n\<cr>" 
    redir END 
    echo l:count 
endfunction 

在這裏,我嘗試運行「:%S/A:模式// n「來查找文本中模式出現的次數。 與此同時,我嘗試將它放入變量「l:count」中。 然後我試着迴應我得到的計數,但是當我嘗試這樣做時沒有任何反應。

所以最後我在寫函數的問題是我不能將命令執行結果寫入變量。

如果您有其他解決方案 - 請向我描述。

更新: 對不起,我的錯誤描述。我想只刪除字符串,它在文本中具有模式雙胞胎。

+0

是否要刪除?還是你想計算你的模式在你的緩衝區匹配的次數? –

+0

@LucHermitte如果計數大於2,我想刪除每個出現的地方。函數的部分就是我試圖去做的。 – Grandma

回答

0

有很多方法可以統計一個模式的發生,而且我很確定這個主題存在Q/A。讓我們以另一種方式來做,並與下一步進行連鎖。 (是的,這完全是混淆的,但它允許以編程方式獲取的信息,而不需要重定向後解析的:substitute本地化的結果。)

" declare a list that contain all matches 
let matches = [] 

" replace each occurrence of the "pattern" with: 
" the result of the expression "\=" that can be 
" interpreted as the last ([-1]) element of the 
" list "matches" returned by the function (add) 
" that adds the current match (submatch(0)) to the 
" list 
:%s/thepattern/\=add(matches, submatch(0))[-1]/gn 
" The big caveat of this command is that it modifies 
" the current buffer. 
" We need something like the following to leave it unmodified: 
:g/thepattern/call substitute(getline('.'), 'thepattern', '\=add(counter, submatch(0))[-1]', 'g') 
" Note however that this flavour won't work with multi-lines patterns 

" Now you can test the number of matches or do anything fancy with it 
if len(matches) > 1 
    " replaces matches with nothing 
    :%s/thepattern//g 
endif 

只有當你想將其定義爲你需要的功能玩:

exe 'normal :%s/'.escape(a:pattern, '/\').'/replacement..../flags....' 
1

我不知道如果我正確地理解你的問題,但我假設你要刪除其中至少有2場比賽都行。如果是這樣的話,你可以使用下面的命令:

:g/\(__pattern__.*\)\{2,}/d 

這是如何工作的,它會刪除所有的地方有一個匹配(:g/../d)的線。 該模式由一組(\(..\))組成,需要至少匹配2次(\{2,})。該模式最後有一個.*,因此它匹配模式匹配之間的所有內容。

相關問題