Grant McLean
Grant McLean

Reputation: 6998

Vim regex - hex character in replacement?

I want to do a global substitution over a range of lines in Vim:

:s/pattern/replacement/g

The 'pattern' is one character in a set, e.g. [BEINS] and the 'replacement' is a single character. However, the wrinkle is that the single character is given to me as the 2 digit hex representation of the character in ASCII/Unicode. Obviously I could look up a hex ASCII chart to see that for example 5F is the underscore character then I could type _ in the replacement part of the regex.

Is there a way to instead type the hex in the righthand side of the regex?

Things I tried that didn't work include:

:%s/[BEINS]/\x5F/g
:%s/[BEINS]/\\x5F/g

On my Linux workstation I can type Ctrl-Shift-U followed by a hex code followed by Enter but I was wondering if there was a Vim-specific way to put the hex in the replacement part of the regex.

Upvotes: 1

Views: 2781

Answers (2)

SergioAraujo
SergioAraujo

Reputation: 11800

You can use:

:%s/[BEINS]/\="\x5F"/gc

The magic:

1 - Use the expression register `\=`
2 - use double quotes

Upvotes: 2

Anurag Peshne
Anurag Peshne

Reputation: 1547

You can try using ctrl+v

:%s/[BEINS]/<ctrl>-vx5F/gc

Here's vim help page on ctrl+v:

With CTRL+V the decimal, octal or hexadecimal value of a character can be entered directly. This way you can enter any character, except a line break (, value 10). There are five ways to enter the character value:

first char      mode         max nr of chars   max value
(none)          decimal            3            255
o or O          octal              3            377      (255)
x or X          hexadecimal        2            ff       (255)
u               hexadecimal        4            ffff     (65535)
U               hexadecimal        8            7fffffff (2147483647)

Upvotes: 5

Related Questions