Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Emacs regex wordWord boundary (specifically concerning underscores)

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?

like image 406
nsimplex Avatar asked May 09 '11 11:05

nsimplex


People also ask

What does \b mean in regex?

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).

What character would you use to start a regular expression pattern at a word boundary?

The metacharacter \b is an anchor like the caret and the dollar sign. It matches at a position that is called a “word boundary”.

What is 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.


1 Answers

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.

like image 188
Gilles 'SO- stop being evil' Avatar answered Sep 28 '22 10:09

Gilles 'SO- stop being evil'