- Forward


Regular Expressions
An Introduction with Examples in Java


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu

Print

Overview
Back SMYC Forward
  • What is a Regular Expression?
    • A sequence of characters that defines a search pattern
  • What are Regular Expressions Used For?
    • Searching (i.e., finding all sequences of characters in a source that match the pattern)
    • Validating (i.e., ensuring that a sequence of characters has certain properties)
Types of Characters
Back SMYC Forward
  • Regular Characters:
    • Literals
  • Metacharacters:
    • Characters that describe other characters
Metcharacters
Back SMYC Forward
  • Some You've Seen Before:
    • \t, \n, and \r
    • \xhh (hexadecimal hh)
  • Some New Ones:
    • \f (form feed)
    • \a (alert/bell)
    • \e (escape)
    • \cx (control x)
Character Classes
Back SMYC Forward
  • Predefined:
    • . (any character)
    • \d (any digit), \D (any non-digit)
    • \s (any whitespace), \S (any non-whitespace)
  • User Defined:
    • [abc] (a, b or c), [^abc] (any character but a, b, or c)
    • [a-zA-z] (a through z or A through Z)
    • [a-z&&[d-f]] (intersection of a through z and d through f)
    • [a-z&&[^b]] (a through z except b)
Boundaries
Back SMYC Forward
  • Line Boundaries:
    • ^ (beginning of a line)
    • $ (end of a line)
  • Word Boundaries:
    • \b (word boundary)
    • \B (non-word boundary)
Quantifiers and Operators
Back SMYC Forward
  • Quantifiers:
    • X? (X 0 or 1 times)
    • X* (X 0 or more times)
    • X+ (X 1 or more times)
    • X{n} (X exactly n times)
    • X{n,} (X at least n times)
    • X{n,m} (X at least n but not more than mtimes)
  • Logical Operators:
    • XY (X followed by Y)
    • X|Y (X or Y)
Encapsulation in Java
Back SMYC Forward
  • "Raw":
    • Use a String
  • "Processed":
    • Use a Pattern (created by a call to the static Pattern.compile(String) method)
Use in Java
Back SMYC Forward
  • String.split():
    • Is passed a String representation of a regular expression
  • String.replaceFirst() and String.replaceAll():
    • Replace occurences of a regular expression
  • String.matches():
    • Determines if a String matches a regular expression
Use in Java (cont.)
Back SMYC Forward
Some Examples
javaexamples/basics/RegularExpressions.java (Fragment: 0)
 
Use in Java (cont.)
Back SMYC Forward
  • Pattern.matches():
    • Searches a String for a regular expression
  • Matcher :
    • Constructed using a Pattern object's matcher(String) method
    • Has a matches() that does the work
Use in Java (cont.)
Back SMYC Forward
A Validation Examples
javaexamples/basics/RegularExpressions.java (Fragment: 1)
 
There's Always More to Learn
Back -