Matching Java method signatures with sed

In the process of removing PMD warnings from our main product at work I was trying to automate some parts of this process by using sed (Stream EDitor), a command line program common on all Unices (such as OS X and Linux). I had already been using a regex in Vim to do remove final modifiers from methods on a file by file basis, but thought it might be quicker to do this using «find» and «sed» in stead. Boy was I wrong🙂 But mainly just because of the different regex dialect of sed that took me a long time to figure out.

The problem was mainly due to trying to match square brackets, such as in «final public int[] myMethod(int[] args)». To substitute this expression in Vim with «public int[] myMethod(int[] args)» I used the following expression:

s/final \([_a-zA-Z0-9\[\]<> ]*\)(/\1(/

The problem was that sed did not cope well with the same expression. After reading up on sed’s syntax on the man page for «re_format» I found out that the left square bracket had to follow immediately after the right and that the right square bracket would need to be escaped. Why this inconsistency? I have no idea. But this means that to match an expression such as «int[]» I would need a regex like this «[]\[a-z]». So the equivalent expression of the Vi regex above is

s/final \([]\[_a-zA-Z<> ]*\)/\1/

This could be used to replace all final modifiers from methods in Java source. A document like
final public class Test {
final public void method1() { }
final public List<Integer> method2() { }
final public List<Integer> method3() { }
final public int[] method4(List<Integer> liste) { }
public List<Integer> non_final_method() { }
}

would turn into
final public class Test {
public void method1() { }
public List<Integer> method2() { }
public List<Integer> method3() { }
public int[] method4(List<Integer> liste) { }
public List<Integer> non_final_method() { }
}

Legg igjen en kommentar

Fyll inn i feltene under, eller klikk på et ikon for å logge inn:

WordPress.com-logo

Du kommenterer med bruk av din WordPress.com konto. Logg ut / Endre )

Twitter picture

Du kommenterer med bruk av din Twitter konto. Logg ut / Endre )

Facebookbilde

Du kommenterer med bruk av din Facebook konto. Logg ut / Endre )

Google+ photo

Du kommenterer med bruk av din Google+ konto. Logg ut / Endre )

Kobler til %s

%d bloggers like this: