Beliebte Suchanfragen

Cloud Native

DevOps

IT-Security

Agile Methoden

Java

|
//

Pattern Matching – Java im Vergleich zu Perl

30.10.2009 | 4 Minuten Lesezeit

„Perl is born to pattern match.“ – Ich denke das kann man ohne Übertreibung so schreiben. Perl löst dieses Problem einfach extrem effizient und elegant. Das folgende kleine Skript zeigt ein paar Beispiele für reguläre Ausdrücke und deren Anwendung in Perl. Wobei ich hoffe, dass mich nicht gleich ein Blitz erschlägt, da ich es wage Perl-Code in unseren Blog zu schreiben, der ja ansonsten eher von Java dominiert wird ;-).

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}

In Java gestaltet sich die ganze Sache schon ein weniger schwieriger, da an dieser Stelle die strenge Objektorientierung etwas unhandlich ist. Es werden die Klassen Pattern und Matcher benötigt. Dabei lehnt sich insbesondere die Pattern-Klasse eng an die Perl-Implementierung an, übernimmt die entsprechenden Ausdrücke und bietet auch passende Operatoren an, z.B. Pattern.CASE_INSENSITIVE für den i-Operator und Pattern.MULTILINE für den m-Operator. Der g-Operator auf der anderen Seite wird durch die Methode replaceAll(…) der Matcher-Klasse nachgebildet.

Das obige Skript als Java-Programm sieht damit wie folgt aus:

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}

Die Ähnlichkeit in der Anwendung wird hier gut sichtbar. Es muss nur bedacht werden, dass ein String in Java immer ein String bleibt und daher ein „\“ mit einem „\“ escaped werden muss. Dies führt dann zu Ausdrücken wie Pattern.compile(„(\\\\special)“), ist aber letzten Endes kein Problem. Die Ausgabe der Programme ist in beiden Fällen identisch:

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

Heisst es also besser zu Perl zu greifen für Applikationen, die viel mit Pattern Matching arbeiten müssen? Nein, es gibt auch eine Alternative für Java-Fans und die lautet Groovy . Denn Groovy unterstützt eine Syntax die wirklich denkbar nah an Perl herankommt. Eine Idee wie das aussieht bekommt man hier . Auf der anderen Seite ist so ein kleines Perl-Skript ab und zu ja durchaus auch nicht zu verachten :-).

|

Beitrag teilen

Gefällt mir

0

//

Weitere Artikel in diesem Themenbereich

Entdecke spannende weiterführende Themen und lass dich von der codecentric Welt inspirieren.

//

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.