2017-02-15 79 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,})。该模式最后有一个.*,因此它匹配模式匹配之间的所有内容。

相关问题