On Mon, 14 Sep 2015 at 10:52am +0200, Niels Kobschaetzki wrote:

I have a problem with a substitution with a simple regex. I want to
change occurrences of page numbers and years that are using a hyphen, to
an en-dash. Something like "308-309" should become "308--309".
My best try so far is:

:s/\d-\d/\1--\2

But this creates 30--09. My understanding is that \1 and \2 keep the
value of the content of \d. Apparently not for whatever reason. What can
I do to get this replacement working?

No. \d stands for any digital number, thus you're replacing "<number>-<number>" with "--". You need to use \( and \) for grouping if you like:

    :%s/\(\d\)-\(\d\)/\1--\2/

or shorter:

    :%s/\v(\d)-(\d)/\1--\2/

What I would do (intuitively), however, is to mark the substring to be replaced with \zs and \ze:

    :%s/\d\zs-\ze\d/--/

this considers the overall context, however, replaces only what is in between \zs and \ze.

Hope this helps.

Best,
Claus

Reply via email to