JMU
Regular Expressions
An Introduction with Examples in Java


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu


Overview
Types of Characters
Metcharacters
Character Classes
Boundaries
Quantifiers and Operators
Encapsulation in Java
Use in Java
Use in Java (cont.)
Some Examples
javaexamples/basics/RegularExpressions.java (Fragment: 0)
                boolean ok;
        String  s, t, u;

        t = "David Bernstein \n CS149 \n CS159";
        s = "yes";        

        // A search (and Replace) Example:
        //   Replace any whitespace in t with a tab 
        u = t.replaceAll("\\s+", "\t");

        // A Validation Example:
        //   Check if s matches "true", "True", "yes", or "Yes"
        ok = s.matches("[tT]rue|[yY]es");
        
Use in Java (cont.)
Use in Java (cont.)
A Validation Examples
javaexamples/basics/RegularExpressions.java (Fragment: 1)
                // A valid phone number consists of an x and 4 digits or
        // 3 digits, a dash or dot, and 4 digits
        
        Matcher validator;        
        Pattern phone;
        phone = Pattern.compile("x\\d\\d\\d\\d|\\d\\d\\d[-.]\\d\\d\\d\\d");

        for (int i=0; i<args.length; i++)
        {
            validator = phone.matcher(args[i]);        
            if (validator.matches())
            {
                System.out.println(args[i]);
            }
        }