我正在使用vscode vimplugin。我有一堆像这样的行:
Terry,169,80,,,47,,,22,,,6,,
我想删除第一个逗号之后的所有字母数字字符所以我得到:
Terry,,,,,,,,,,,,,
在命令模式下,我尝试了:
s/^.+,[a-zA-Z0-9-]+//g
但这似乎没有做任何事情。我怎样才能使它工作?
编辑:
s/^[^,]+,[a-zA-Z0-9-]+//g
+
是贪婪的;^.+,
吃掉整行,直到最后一个,
.
用[^,]
代替点(意思是"任何字符"),意思是"除了逗号之外的任何字符"。然后^[^,]+,
表示">第一个之前的任何字符"。comma" .
您的要求的问题是,您希望在开始使用^
锚,所以您不能使用标志g
锚-任何替代将完成一次。我可以解决这个难题的唯一方法是使用表达式:匹配并保留锚定文本,然后使用函数substitute()
与标志g
。
我设法用下面的表达式:
:s/(^[^,]+)(,+)(.+)$/=submatch(1) . submatch(2) . substitute(submatch(3), '[^,]', '', 'g')/
让我把它分成几部分。搜索:
(^[^,]+) — first, match any non-commas
(,+) — any number of commas
(.+)$ — all chars to the end of the string
替换:
= — the substitution is an expression
看到http://vimdoc.sourceforge.net/htmldoc/change.html sub-replace-expression
submatch(1) — replace with the first match (non-commas anchored with ^)
submatch(2) — replace with the second match (commas)
substitute(submatch(3), '[^,]', '', 'g') — replace in the rest of the string
对substitute()
的最后一次调用很简单,它用空字符串替换所有非逗号。
p。在真正的vim
测试,而不是vscode。