I am trying to replace all occurrences of a whole word on emacs (say foo) using M-x replace-regexp.
The problem is that I don't want to replace occurrences of foo in underscored words such as word_foo_word
If I use \bfoo\b to match foo then it will match the underscored strings; because as I understand emacs considers underscores to be part of word boundaries, which is different to other RegEx systems such as Perl.
What would be the correct way to proceed?
The word boundary \b matches positions where one side is a word character (usually a letter, digit or underscore—but see below for variations across engines) and the other side is not a word character (for instance, it may be the beginning of the string or a space character).
The metacharacter \b is an anchor like the caret and the dollar sign. It matches at a position that is called a “word boundary”.
A word boundary is a zero-width test between two characters. To pass the test, there must be a word character on one side, and a non-word character on the other side. It does not matter which side each character appears on, but there must be one of each.
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. Symbol constituents include not only word constituents (alphanumerics) but also punctuation characters that are allowed in identifiers, meaning underscores in most programming languages.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With