Beliebte Suchanfragen
|
//

Pattern Matching – Java compared to Perl

30.10.2009 | 4 minutes of reading time

“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 ;-).

1#!/usr/bin/perl -w
2 
3$sampleText = <<END;
4Here is some text that will be used for pattern matching in this example.
5Of course we need some nice outstanding words to match and some \\special
6character and here some 1234 Number that will just do fine. And more ...
7END
8 
9print "Complete Text:\n";
10print $sampleText;
11print "\n";
12 
13#
14# Let's match something easy like the word "outstanding"
15#
16if ($sampleText =~ /(outstanding)/) {
17    print "Pattern found: " . $1 . "\n\n";
18}
19 
20#
21# Let's match two expressions one being a number
22#
23if ($sampleText =~ /(\d+)\s+(Number)/) {
24    print "Pattern found: " . $1 . $2 . "\n\n";
25}
26 
27#
28# Let's match something a bit more complicated like \\special
29#
30if ($sampleText =~ /(\\special)/) {
31    print "Pattern found: " . $1 . "\n\n";
32}
33 
34#
35# Let's match something ignoring the case and that is the first word of
36# the input string.
37#
38if ($sampleText =~ /^(here)/i) {
39    print "Pattern found: " . $1 . "\n\n";
40}
41 
42#
43# Let's replace all occurrences of the word "and" with "NOAND"
44# (without the \s+ we would also change the "and" in outst-and-ing)
45#
46if ($sampleText =~ s/(\s+)(and)(\s+)/$1NOAND$3/gi) {
47    print "Changed Text:\n" . $sampleText . "\n\n";
48}

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:

1import java.util.regex.Pattern;
2import java.util.regex.Matcher;
3 
4public class PMatch {
5 
6    public String sampleText = "Here is some text that will be used for"
7            + " pattern matching in this example.\n"
8            + "Of course we need some nice outstanding words to match"
9            + " and some \\special\n"
10            + "character and here some 1234 Number that will just do"
11            + " fine. And more ...";
12 
13    public void printText() {
14        System.out.println("Complete Text:\n" + sampleText + "\n");
15    }
16 
17    public void matchStandardText() {
18        Pattern p = Pattern.compile("(outstanding)");
19        Matcher m = p.matcher(sampleText);
20        if (m.find()) {
21            System.out.println("Pattern found: " + m.group(1) + "\n");
22        }
23    }
24 
25    public void matchTwoExpressions() {
26        Pattern p = Pattern.compile("(\\d+)\\s+(Number)");
27        Matcher m = p.matcher(sampleText);
28        if (m.find()) {
29            System.out.println("Pattern found: " + m.group(1) + m.group(2)
30                    + "\n");
31        }
32    }
33 
34    public void matchSecialChar() {
35        Pattern p = Pattern.compile("(\\\\special)");
36        Matcher m = p.matcher(sampleText);
37        if (m.find()) {
38            System.out.println("Pattern found: " + m.group(1) + "\n");
39        }
40    }
41 
42    public void matchIgnoreCase() {
43        Pattern p = Pattern.compile("^(here)", Pattern.CASE_INSENSITIVE);
44        Matcher m = p.matcher(sampleText);
45        if (m.find()) {
46            System.out.println("Pattern found: " + m.group(1) + "\n");
47        }
48    }
49 
50    public void replace() {
51        Pattern p = Pattern.compile("(\\s+)(and)(\\s+)",
52                Pattern.CASE_INSENSITIVE);
53        Matcher m = p.matcher(sampleText);
54        if (m.find()) {
55            sampleText = m.replaceAll(m.group(1) + "NOAND" + m.group(3));
56            System.out.println("Changed Text:\n" + sampleText);
57        }
58    }
59 
60    public static void main(String[] args) {
61        PMatch pMatch = new PMatch();
62 
63        pMatch.printText();
64        pMatch.matchStandardText();
65        pMatch.matchTwoExpressions();
66        pMatch.matchSecialChar();
67        pMatch.matchIgnoreCase();
68        pMatch.replace();
69    }
70}

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.

1Complete Text:
2Here is some text that will be used for pattern matching in this example.
3Of course we need some nice outstanding words to match and some \special
4character will just do fine. And more ...
5 
6Pattern found: outstanding
7 
8Pattern found: 1234Number
9 
10Pattern found: \special
11 
12Pattern found: Here
13 
14Changed Text:
15Here is some text that will be used for pattern matching in this example.
16Of course we need some nice outstanding words to match NOAND some \special
17character will just do fine. NOAND more ...

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 :-).

|

share post

//

More articles in this subject area

Discover exciting further topics and let the codecentric world inspire you.

//

Gemeinsam bessere Projekte umsetzen.

Wir helfen deinem Unternehmen.

Du stehst vor einer großen IT-Herausforderung? Wir sorgen für eine maßgeschneiderte Unterstützung. Informiere dich jetzt.

Hilf uns, noch besser zu werden.

Wir sind immer auf der Suche nach neuen Talenten. Auch für dich ist die passende Stelle dabei.