Gaut
Gaut

Reputation: 1387

vim regex multiline: search works, match() doesn't

Let's say I have this buffer:

a
b
c
(
1
2
3
)
@
#
$

I would like, in a vimscript to get the contents of line between parentheses.

/(\n\(.\n\)*)

highlights exactly what I want. But I don't succeed to get this with something like:

let pattern = '(\n\(.\n\)*)'
match(getline(1, '$'), pattern)

I try a lot of stuffs, such as:

match(join(getline(1,'$'), '\n'), pattern)  

, even double quotes for pattern, but nothing works... Any idea ?

(my aim is not necessary to make this match() works, but just to get the result from a buffer to a vimscript)

Upvotes: 1

Views: 182

Answers (1)

yolenoyer
yolenoyer

Reputation: 9445

With your first try (match(getline(1, '$'), pattern)), Vim tries to find the pattern inside each line; as your pattern is multi-line, it never matches.

So, your second try goes to a right direction, because you try to join the lines, then the pattern would effectively match... Unless you use '\n' as a glue for the join : this string is litterally replaced by a backslash \ followed by an n character. Just replace single quotes by double quotes, then special chars will be parsed.

So, this version will work better:

echo matchstr(join(getline(1,'$'), "\n"), pattern)

Upvotes: 3

Related Questions