7

I have text saved in a variable, for example, like this:

let text = getline(line(".")-1)

How do I check if the text matches a regular expression? I'm expecting something like this:

let text = getline(line(".")-1)
if regexp_match(text, "^[Ss]tuff$")
    dostuff
endif
gvlasov
  • 18,638
  • 21
  • 74
  • 110
  • 1
    Well... Tried typing :h regex and pressing tab attempting to find something in help that could, well, help. Are you sure that "what have you tried?" is an appropriate question when someone asks for a way to do something? – gvlasov Oct 02 '12 at 23:05
  • 2
    Well, a quick google search of "vim-script regex" returns as it's top result: http://stackoverflow.com/questions/3135322/regex-in-vimscript . It would help if you do some legwork before asking a question. – CrazyCasta Oct 02 '12 at 23:25
  • 1
    YMMV with legwork depending on the paths you take. I came here with a Google search of `vimscript if regex` first, so thanks for providing this link. Better still, the own research you encouraged the OP to do provides the actual answer that they and I were looking for, which your link does not. – Medlock Perlman Jan 12 '15 at 12:52

1 Answers1

10

Made some more research and found out that what I needed is =~# operator which is used to check if some text matches a regexp:

if "text"=~#"^te.."
    echo "Matches!"
kdavh
  • 404
  • 6
  • 13
gvlasov
  • 18,638
  • 21
  • 74
  • 110
  • Sometimes it's better to use single quotes `'` instead of double quotes `"` around your regex. https://vi.stackexchange.com/questions/28233/why-doesnt-regex-work-in-vimscript-while-it-does-in-normal-search – alec Nov 30 '20 at 14:51