Google

Jun 20, 2013

Notepad++ with power of regex as a productivity tool for developers

This is an extension to my post entitled Notepad++ plugin for viewing JSON data and other benefits to demonstrate the power of Notepad++ and regular expression.

This post is based on a industrial example where you have a CSV file where you want to add quotes (i.e. ") around it. For example

Convert text like:

 
BA555,04-May-2013,04-04-2013,12358,AUSTRALIAN BONDS,,86776.00,AUD,86776,Application,,Capital


To

"BA555","04-May-2013","04-04-2013","12358","AUSTRALIAN BONDS","","86776.00","AUD","86776","Application","","Capital"

Another reason you might want to do this in Java is to construct a String array or list as shown below.

       List<string> asList = Arrays.asList(new String[]
        {
            "BA555", "04-May-2013", "04-04-2013", "12358", "AUSTRALIAN BONDS", "", "86776.00", "AUD", "86776",
            "Application", "", "Capital"
        });

Now let's see how we can use notepad++ find/replace function to add quotes around each entry using its find/replace with regular expressions as shown below.


As you can see

Find what regular expression is:  ([^,]*)(,?) , which means 0 or more characters but "," as first group stored in "\1" followed by 0 or 1 "," (i.e. optional ,), and grouped as \2.

Replace with regular expression is: "\1"\2 where " is added then followed by \1, which is the value captured like BA555 and then followed by ", and followed by optional ",".

Similar approaches can be used for formatting other bulk records like removing spaces, adding quotes, replacing new line characters with tabs, replacing tabs with new lines, replacing commas with new lines, etc.

Here is an example for replacing "," with new lines.



The output will be

 
BA555
04-May-2013
04-04-2013
12358
AUSTRALIAN BONDS

86776.00
AUD
86776
Application

Capital

Labels: ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home