Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vim regular expression to remove all but last two digits of number

Tags:

regex

vim

I have following text in a file

23456789

When I tried to replace the above text using command

1,$s/\(\d\)\(\d\d\d\)\(\d\d\)*\>/\3\g

I am getting 89. Shouldn't it be 6789? Can anyone tell me why it is 89.

like image 492
chappar Avatar asked Jan 14 '09 11:01

chappar


1 Answers

As written, your regex captures one digit, then three digits, then any number of groups of two digits each. The third match will, therefore, always be two digits if it exists. In your particular test case, the '89' is in \4, not \3.

Changing the regex to

 1,$s/\(\d\)\(\d\d\d\)\(\d\d\+\)\>/\3\g

will give you '6789' as the result, since it will capture two or more digits (up to as many as are there) in the third group.

like image 88
Dave Sherohman Avatar answered Sep 30 '22 17:09

Dave Sherohman