1

Some modes treat underscores as word boundaries.

I am using evil via spacemacs. I am trying to use a vim/sed style :%s/foo/bar/g search and replace, but operate only on whitespace delimited words, not underscores.

As an example, if I have the following:

num_foos_
foos_

and I want to rename only foos_ to bars_.

I have tried the following:

  • :%s/foos_/bars_/g : matches both num_foos_ and foos_
  • :%s/\bfoos_/bars_/g : matches both num_foos_ and foos_ (I guess because _ is a word boundary, so \b matches num_foos_)
  • :%s/\bfoos_\b/bars_/g : matches neither (I guess because _ is a word boundary, and there is no word after the trailing _)
  • :%s/\<foos_/bars_/g : matches both num_foos_ and foos_ (I guess for the same reasons as \b)

How can I match only foos_ and not num_foos_?

1

The required syntax is %s/\_<foos_\_>/bars_/g

As mentioned in this SO answer:

The regexp \<foo\> or \bfoo\b matches foo only when it's not preceded or followed by a word constituent character (syntax code w, usually alphanumerics, so it matches in foo_bar but not in foo1).

Since Emacs 22, the regexp \_<foo_bar\_> matches foo_bar only when it's not preceded or followed by a symbol constituent character. A symbol constituent is either a word constituent or a character with syntax _. Most programming mode define _ to be a symbol constituent.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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