Χρήση κανονικών εκφράσεων

Παράδειγμα: Εύρεση κανονικών εκφράσεων σε αρχείο

/*
 * Globally match regular expression and print
 * Modelled after the Unix command with the same name
 * D. Spinellis, January 2004
 */

import java.util.regex.*;
import java.io.*;

class Grep {
        public static void main(String args[]) {
                if (args.length != 2) {
                        System.err.println("Usage: Grep pattern file");
                        System.exit(1);
                }

                Pattern cre = null;             // Compiled RE
                try {
                        cre = Pattern.compile(args[0]);
                } catch (PatternSyntaxException e) {
                        System.err.println("Invalid RE syntax: " + e.getDescription());
                        System.exit(1);
                }

                BufferedReader in = null;
                try {
                        in = new BufferedReader(new InputStreamReader(new FileInputStream(args[1])));
                } catch (FileNotFoundException e) {
                        System.err.println("Unable to open file " + args[1] + ": " + e.getMessage());
                        System.exit(1);
                }

                try {
                        String s;
                        while ((s = in.readLine()) != null) {
                                Matcher m = cre.matcher(s);
                                if (m.find())
                                        System.out.println(s);
                        }
                } catch (Exception e) {
                        System.err.println("Error reading line: " + e.getMessage());
                        System.exit(1);
                }
        }
}

Παράδειγμα:

java Grep "abo" /usr/dict/words
...
sabotage
seaboard
taboo
thereabouts
turnabout
vagabond
whereabout
...

java Grep "^abo" /usr/dict/words
aboard
abode
abolish
abolition
abominable
abominate
aboriginal

java Grep bent /usr/dict/words
absorbent
bent
benthic
debenture
incumbent
recumbent

java Grep "bent$" /usr/dict/words
absorbent
bent
incumbent
recumbent

java Grep "[^AEIOUYaeiouy]{5,}" /usr/dict/words
angstrom
Armstrong
birthplace
bremsstrahlung
corkscrew
Dijkstra
downstream
hardscrabble
jockstrap
Knightsbridge
lengthly
Nietzsche
nightclub
offspring
postscript
Rothschild
...

java Grep "(.)(.)(.)\3\2\1" /usr/dict/words
braggart
Brenner
collocation
diffident
dissident
glossolalia
grammar
grammarian
installation
staccato
suffuse