Pergunta

I am trying to write a regular expression in vi to match any whitespace character followed by any digit. Then, at each match, insert a dollar sign between the whitespace and the digit. Here is an example:

A1234 12 14 B1234
B1256 A2 14 C1245
C1234 34 D1 1234K

The correct regex would produce this:

A1234 $12 $14 B1234
B1256 A2 14 C1245
C1234 $34 D1 $1234K

I realize I need to use a back reference, but I can't quite seem to write the correct regex. Here is my attempt:

:'<,'>/(\s\d)/\s\1\$/g

Also, I have Vim's default regex mode turned off (vnoremap / /\v).

Thanks for the help.

Foi útil?

Solução

You need to escape the parentheses to make them work as groupings rather than as actual matches in the text, and not escape the $. Like so:

:%s/\(\s\)\(\d\)/\1$\2/g

This worked for me in vim (using standard magic setting).

Edit: just realized that your non-standard regex settings cause you having the escape 'the other way around'. But still, the trick, I think, is to use two groups. With your settings, this should work:

:%s/(\s)(\d)/\1$\2/g

Outras dicas

Using a back reference is not inevitable. One can make a pattern to match zero-width text between a whitespace character and a digit, and replace that empty interval with $ sign.

:'<,'>s/\s\zs\ze\d/$/g

(See :help /\zs and :help /\ze for details about the atoms changing the borders of a match.)

My first thought is:

:%s/(\b\d)/$\1/g

with \b is for word boundary. But it turns out that \b doesn't mean word boundary in Vim regex, rather \< and \> for the start and end of the word. So the right answer would be:

:%s/\(\<\d\)/$\1/g

(Making sure to escape the capturing parenthesis.)

Sorry that my correction came so late.

Not sure abt the exact vim syntax, but regEx syntax should be this:

search expr - "(\s)([\d])"
replacement expr - "\1 $\2"

so something like:

/(\s)([\d])/\1 $\2/g

This will do the job for you (without using groups):

:%s/\s\@<=\d\@=/$/g

Explanation:

  • %: On every line...
  • s: Substitute...
  • /: Start of pattern
  • \s: Whitespace
  • \@<=: Match behind (zero-width)
  • \d: Digit
  • \@=: Require match (zero-width)
  • /: End of pattern, start of replacement
  • $: What you asked for!
  • /: End of replacement
  • g: Replace all occurrences in the line.
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top