Search for pattern in the first few lines of a buffer

11 views
Skip to first unread message

Lifepillar

unread,
Jun 20, 2021, 7:00:03 AM6/20/21
to vim...@googlegroups.com
I need to programmatically search for a pattern in the first ten lines
of a given buffer, and save the match in a variable when found. Say, the
pattern is:

% KEY = value

I need to extract the value if the above appears in the first lines of
the buffer. Of course, the state of the buffer's window, such as the
cursor's position, etc., and the content of registers should not be
affected. How would you do that?

Thanks,
Life.

Yegappan Lakshmanan

unread,
Jun 21, 2021, 1:28:10 AM6/21/21
to vim_use
Hi,
You can use getbufline() to read the first 10 lines of the buffer
as a list and then use match() to find the index of the item matching
a pattern in the list. You can then use substitute() or matchstr()
to extract the value.

Regards,
Yegappan

Lifepillar

unread,
Jun 21, 2021, 5:52:27 AM6/21/21
to vim...@googlegroups.com
That is a simple strategy!

Thanks,
Life.

Reply all
Reply to author
Forward
0 new messages