Categories
Uncategorized

Regex, Non-greedy Matching and Sets – Vim

We start with the string

This is the string that needs to be matched and 01 02 040 542 changed

and we want to end up with

This is the changed string.

Non-greedy

First thing we do is delete everything from `string’ to `changed’ using .\{-} to mean `everything between’

:s/that.\{-}542//

and we end up with

This is the string changed

Using sets

We can divide the strings into sets by encapsulating them in \( \).

We can also use \a\{6} and \a\{7} to find words that are 6 alphabetic characters (`string’) and 7 alphabetic characters long (`changed’) respectively.

So in essence we will be splitting it up like this

(This is the) (string) (changed)
   set 1        set 2    set 3

Then we put it all back together with group 3 in the middle and a full stop at the end, calling back each set like so: \1 for set 1, \2 for set 2 and \3 for set 3.

The final command looks like this

s/\(^.\{-}the\) \(\a\{6}\) \(\a\{7}\)/\1 \3 \2./

Which returns

This is the changed string.

DONE!

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s