Vimscript:获取正则表达式的所有匹配字符串

时间:2022-03-19 04:53:36

In vimscript, we have substitute function which will accept flag 'g' to substitute all occurrences.

在vimscript中,我们有替换函数,它将接受标志'g'来替换所有出现的事件。

Is there a way to get all the matches strings?

有没有办法获得所有匹配字符串?

For example, with string 'x y z', we can use substitute('x y z', '[a-z]', 'abc', 'g') to change it into abc abc abc.

例如,使用字符串'x y z',我们可以使用替换('x y z','[a-z]','abc','g')将其更改为abc abc abc。

However, is there any way to get the individual characters ['x', 'y', 'z']?

但是,有没有办法获得单个字符['x','y','z']?

I know we can use match() to get the matched position, and matchstr() to get the matched string. But if I want to iterate through all matches, I have to call both functions which I think is not the efficient way.

我知道我们可以使用match()来获取匹配的位置,并使用matchstr()来获取匹配的字符串。但是如果我想迭代所有的匹配,我必须调用我认为不是有效方式的两个函数。

So Is there any efficient way for getting all matches of a string in vimscript?

那么在vimscript中获取字符串的所有匹配是否有效?

2 个解决方案

#1


9  

You can use a substitute with a sub-replace-expression to capture all the matches.

您可以使用sub-replace-expression的替换来捕获所有匹配项。

let str = 'a b c'
let lst = []
call substitute(str, '[a-z]', '\=add(lst, submatch(0))', 'g')

For more help see:

有关更多帮助请参阅:

:h sub-replace-expression
:h substitute
:h add()
:h submatch()

#2


1  

If you can negate the regexp to match what's not needed, you can use split(); it will remove all matches from the string and return a List of the remainders in bewtween:

如果你可以否定正则表达式以匹配不需要的正则表达式,你可以使用split();它将从字符串中删除所有匹配项并返回bewtween中剩余项的List:

:echo split('x y z', ' ')
['x', 'y', 'z']

#1


9  

You can use a substitute with a sub-replace-expression to capture all the matches.

您可以使用sub-replace-expression的替换来捕获所有匹配项。

let str = 'a b c'
let lst = []
call substitute(str, '[a-z]', '\=add(lst, submatch(0))', 'g')

For more help see:

有关更多帮助请参阅:

:h sub-replace-expression
:h substitute
:h add()
:h submatch()

#2


1  

If you can negate the regexp to match what's not needed, you can use split(); it will remove all matches from the string and return a List of the remainders in bewtween:

如果你可以否定正则表达式以匹配不需要的正则表达式,你可以使用split();它将从字符串中删除所有匹配项并返回bewtween中剩余项的List:

:echo split('x y z', ' ')
['x', 'y', 'z']