Replace all integers until a certain character

I am making a table which has chemical formulas in the first column so I need the integers as subscripts to use it in a LaTex file.

I want to transform CH4 & to CH$_4$ &, C2H5 & to C$_2$H$_5$ & and so on. How do I select all integers before the occurrence of & in a line and add the suffix and a prefix to it?

• Do you want to operate on all the integers before the first occurrence of an ampersand, or all the integers that come before any ampersand. Or is there guaranteed only to be one ampersand on the line? – Rich Dec 5 '18 at 22:04

Presuming you are only interested in replacing the numbers before the first ampersand on each line, one fairly crude way to do it is to first split the lines on the first ampersand, then perform the substitutions, and then rejoin the lines:

:g/\&/norm! f&i^M
:g/^[^&]/s/\d\+/$_\0$/g
:g/^&/norm! kJ

In the first line, the ^M is a literal carriage return which you can enter by pressing: Ctrl-VEnter. A more copy-and-pastable version of that line is as follows:

:execute "g/\&/norm! f&i\<CR>"

If, on the other hand, you want to replace any integers that come before any ampersand, or if each line is guaranteed only to have one ampersand, then a one-liner is possible:

%s/\d\+\ze.*&/$_\0$/g
• I understood the substitution. Could you please explain what the first line means? – nac001 Dec 5 '18 at 23:23
• Yes, sorry, bit short on explanation. I’ll fill in tomorrow if I get a chance, but the first and third lines of the first solution are both using :global to run a :normal command on each line that matches a regexp. :normal just acts as though you pressed the specified keys, so the first line acts as though you visited every line that contains an ampersand and then pressed f&i<CR> i.e. jump to the ampersand and insert a newline. – Rich Dec 5 '18 at 23:53

For this particular problem, the better solution is to instead use the LaTeX package mhchem for typesetting the formulas. A good solution is similar to this:

\documentclass{article}
\usepackage{mhchem}
\usepackage{array}

% This is only used for pretty rules (\toprule, etc)
\usepackage{booktabs}

\def\zzz#1\relax{\ce{#1}}
\newcolumntype{F}{>{\zzz}l<{\relax}@{}}

\begin{document}

\begin{tabular}{Fl}
\toprule
Formula & More \\
\midrule
CH4 & 1 \\
C2H5 & 2 \\
\bottomrule
\end{tabular}

\end{document}