Notepad++ with the power of regex for productivity tutorial

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:


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

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

Converting CSV TO PSV

There are times you want to convert “,” in files to”|”, but not replace the “,” within quotes. For eaexample:

should become

The regex you can use in Notepad++ is

FROM: (“[^”]*”)|,

TO: (?1$1:|)

(“[^”]*”)|, –> pattern matches and captures into Group 1 (i.e. $1 or \1) as anything within quotes any character other than quotes i.e. [^”]*. | is for OR and the ,.

(?1$1:|) –> Group 1 matched ((?1) the Group 1 value should be put back where it was (see the $1 placeholder), else (:) replace the matched string (i.e. the comma) with a pipe symbol.

Java Interview FAQs

800+ Java Interview Q&As