Search

Dark theme | Light theme

December 19, 2008

Use regular expressions for search and replace in NetBeans

NetBeans supports regular expressions for searching and replacing text in the editor. In my last project I had to replace a bit of HTML code with an array. Here is the source HTML code:

<option value="/en/gb/overview.html">United Kingdom</option>
<option value="/en/us/overview.html">United States</option>
<option value="/en/ca/overview.html">Canada</option>
<option value="/nl/nl/overview.html">The Netherlands</option>
<option value="/nl/be/overview.html">Belgium (Dutch)</option>

And this needed to be changed to the following code:

locales["gb_en"] = "index_en_gb.html"
locales["us_en"] = "index_en_us.html"
locales["ca_en"] = "index_en_ca.html"
locales["nl_nl"] = "index_nl_nl.html"
locales["be_nl"] = "index_nl_be.html"

I started out by changing each line, but then I realized I was doing the same thing over and over again (the real list was much bigger than the one in this example). There must be a better way and in NetBeans there is!

We go to Edit | Replace. NetBeans shows the Replace dialog window. In the Find What field we type the following regular expression: ^<option value="/(.*)/(.*)/overview.html">.*</option>.  Notice we define 2 groups between the parenthesis. We use these in the Replace With field where we type locales["$2_$1"] = "index_$1_$2.html". We are almost done, we only must check Regular Expressions and click on the Replace All button.