“Perl is born to pattern match.” – I truly believe that this statement is no exaggeration. Perl is solving this problem in an extremely efficient and elegant way. The following short script is showing some examples for regular expressions in Perl. Hopefully I will not be struck by lightning for posting Perl code in our blog that is otherwise dominated by Java ;-).
Doing the same thing in Java is a bit more tricky as Java’s very strict object-oriented approach makes this a bit bulky. One have to use the classes Pattern and Matcher . Here it can be already seen that the Pattern-class is implemented with a close look to the Perl-implementation. Thus there are similar operators, for example Pattern.CASE_INSENSITIVE for the i-operator and Pattern.MULTILINE for the m-operator. The g-operator is implemented by the method replaceAll(…) from the Matcher-class.
The following code shows the Java-equivalent to the Perl-script shown above:
It becomes quite obvious that there are a lot of similarities. One only has to keep in mind that a String remains a String in Java and thus a “\” has to be escaped with a “\”. This leads then to expressions like Pattern.compile(“(\\\\special)”), but this is of course no problem in the end. The output of both programs is identical.
Does this mean it is better using Perl for applications that are using Pattern Matching intensively? No, luckily there is also an alternative for fans of Java, namely: Groovy . Groovy is supporting a syntax that comes really close to Perl. The examples shown here are giving an idea how this might look like. On the other hand some small Perl-script every now and then is also not to be scoffed at :-).
More articles in this subject area
Discover exciting further topics and let the codecentric world inspire you.
Blog author
Thomas Jaspers
Senior Software Engineer & AI Enthusiast
Do you still have questions? Just send me a message.
Do you still have questions? Just send me a message.