Regular Expressions
An Introduction with Examples in Java |
Prof. David Bernstein |
Computer Science Department |
bernstdh@jmu.edu |
String.split()
:
String
representation of a regular
expressionString.replaceFirst()
and String.replaceAll()
:
String.matches()
:
String
matches a regular
expression
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");
// 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]); } }