1

Imagine I have a file as follows,

10 10
10 11
...
10 20
20 20
20 21
...
20 40
40 40
40 41
...

I know simple regex such as

To search two numbers

/\d\+ \d\+

To search repeated numbers

/\(\d\+\) \1

My question is what is regex pattern such that I can search

10 20
20 40
40 80
...

I want to create regex pattern something of this sort

\(\d\+\) 2*\1

So that I can get multiplication of that earlier group

1

You can use submatch() function and use it to substitute with some pattern on those lines may be. I got it till here:

:%s/\(\d\+\).*\ \(\d\+\).*$/\=(submatch(2)==2*submatch(1))?"YES":"NO"/g

This replaces the lines where if finds the pattern that you requested for with YES.

Not sure how to do it without substitution.

Following for a better answer.

| improve this answer | |
-1

Just looking at something like your last example, this will replace a number with double its value:

s/\d\+/\=submatch(0) * 2/ 

This is known as a sub-replace expression and I go into some depth here, though with an emphasis on string operations: How to run a substitute command on only a certain part of the line

The key is \= which says "everything after this point is to be evaluated as an expression and the result of that evaluation becomes the substituted string". submatch(0) represents the entire matched string. If you use capture groups \(...\) then you can refer to their matched parts with submatch(1..9).

So...

s/\v(\d+) (\d+)/\=submatch(1) * submatch(2)/ 

Will replace two numbers separated by a space with their product.

Beyond that it's pretty much anything goes. You're running vimscript in there so you can call functions, do arithmetic, manipulate strings, and so on.

| improve this answer | |
  • I won't ask why this was downvoted cuz there's clearly no rational reason for it. – B Layer Jul 6 at 17:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.