vim regex

Ever wonder just how useful vim REALLY is? Well, the substitution command in VIM makes it really useful, it supports all sorts of regex, and makes editing very easy and fast assuming that the user knows what he/she is doing. Vim is one of those tools that takes more thinking than doing at the beginning. For example it took me 30 minutes to surround lines from 24 to 35 with =>” and “.  To give you a better picture of my problem look at the below example.

line containing contents foo bar will become =>”foo bar” for arbitrary number of lines.

There are several ways of doing this. One of the ways is by using the Visual block mode to select lines 24 to 35 and press I to insert =>” at the beginning of the lines. Then again select the lines and press A to append to the end of the lines. But I didn’t think this was a satisfactory solution to my problem. What if there were 50 lines that needs to be encapsulated instead of 11 lines? (visual block selection can be a pain sometimes)

So we can use subsitution command :

:24,35s/^.*$/=>"&"/

to solve our problem.

What the command says is that from lines 24 to 35 we are going to substitute the from beginning of the line to the end of the line (denote this as X), with the X but with =>” before it and after it. The & symbol represents the contents which we just matched (in this case it is X).

Here is another useful substitution command you might use

:23s/[a-z]*_*[a-z]*\s*/=>"&",\r/g

The above command takes a line (i.e line 23) of multiple words for example:

23: foo bar lulz cat

to

=>"foo",

=>"bar",

=>"lulz",

=>"cats",

this is specifically useful if you want to construct a large php array of multiple keys and values. What I do is I first type out the words that will be the values then use the above command, then type in the corresponding key for each value. e.g.

array(

1=>"foo",

2=>"bar",

3=>"lulz",

4=>"cats"

);

I hope the above will help you constructing large php arrays as it did for me.

Advertisements

  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

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

%d bloggers like this: