I'm a little confused on VimScript's regex comparison operators.

If I look through :h =~? my understanding is that =~ can be used to do a regex match (with the ? making it case-insensitive).

But this code prints "no":

let s:myVar = "S123"
if s:myVar =~? "^S\d+"
  echo "yes"
  echo "no"

Am I using the =~ operator incorrectly?

1 Answer 1


There are two problems:

  1. You need \+ since you're not using magic.
  2. You're using " instead of '. You need to double escape \: \\d, or use single quotes.

    See :h literal-string:

    literal-string                                          literal-string E115
    'string'                string constant                 expr-'
    Note that single quotes are used.
    This string is taken as it is.  No backslashes are removed or have a special
    meaning.  The only exception is that two quotes stand for one quote.
    Single quoted strings are useful for patterns, so that backslashes do not need
    to be doubled.  These two commands are equivalent: 
            if a =~ "\\s*"
            if a =~ '\s*'


let s:myVar = "S123"
if s:myVar =~? '^S\d\+'
  echo "yes"
  echo "no"

This works as expected.

  • Ah, thanks. So, I think this is what I was going after: if s:myVar =~ '\v^S\d+' Jan 26, 2016 at 20:53
  • 1
    @Jonathan.Brink you can also tack on case insensitivity to the pattern: '\v\c^S\d+'.
    – muru
    Jan 26, 2016 at 20:55
  • nice. Would that be preferable to using =~? Jan 26, 2016 at 20:56
  • 1
    @Jonathan.Brink Depends on how you intend to use it. If you intend to re-use the pattern (keep it in a variable, and do tests in multiple places or something), using \c will centralise the case-insensitivity. Useful for code organization, otherwise I don't think there's a difference.
    – muru
    Jan 26, 2016 at 20:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.