Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vim, How do I get matching word in parenthesis from regex

Tags:

vim

vim-plugin

with vim script,

Let me say that I want to find word "This" from the following expression

match("testingThis", '\ving(.*)')

I tried with some different options, getmatches(), substitute(), not luck yet :(

Is there a way get matches in vim like in ruby or php, i.e. matches[1]

--------------------------EDIT----------------------------

from h function-list, as glts mentioned, I found matchlist() unlike matchstr(), which always returns full matches, like matches[0], it returns full array of matches.

echo matchstr("foo bar foo", '\vfoo (.*) foo')  " return foo bar foo
echo matchlist("foo bar foo", '\vfoo (.*) foo')  " returns ['foo bar foo', 'bar', '', '', '', '', '', '', '', '']
like image 957
allenhwkim Avatar asked Sep 05 '13 17:09

allenhwkim


People also ask

How do you match words in regex?

To run a “whole words only” search using a regular expression, simply place the word between two word boundaries, as we did with ‹ \bcat\b ›. The first ‹ \b › requires the ‹ c › to occur at the very start of the string, or after a nonword character.

How do you use parentheses in regex?

By placing part of a regular expression inside round brackets or parentheses, you can group that part of the regular expression together. This allows you to apply a quantifier to the entire group or to restrict alternation to part of the regex. Only parentheses can be used for grouping.

How do I match a pattern in Vim?

In normal mode, press / to start a search, then type the pattern ( \<i\> ), then press Enter. If you have an example of the word you want to find on screen, you do not need to enter a search pattern. Simply move the cursor anywhere within the word, then press * to search for the next occurrence of that whole word.

What does matching mean in regex?

Matches(String, Int32) Searches the specified input string for all occurrences of a regular expression, beginning at the specified starting position in the string. Matches(String) Searches the specified input string for all occurrences of a regular expression.


1 Answers

In this particular case, you can use matchstr() (which returns the match itself, not the start position), and let the match start after the before-assertion with \zs:

matchstr("testingThis", '\ving\zs(.*)')

In the general case, there's matchlist(), which returns a List of the entire match plus all captured groups. The result is in the first capture group, so the element at index 1:

matchlist("testingThis", '\ving(.*)')[1]
like image 199
Ingo Karkat Avatar answered Sep 22 '22 11:09

Ingo Karkat