70 likes | 203 Vues
This resource explores the concept of regular expressions, a powerful tool used in various programming languages for textual pattern matching. It covers essential aspects, including the structure of regular expressions, examples for matching patterns like phone numbers, and specific implementations in Java. Students will learn how Java's `String` class utilizes methods such as `matches()`, `replaceFirst()`, and `replaceAll()` for effective text manipulation. This material is based on the 9th edition of "Concepts of Programming Languages" by Robert W. Sebesta.
E N D
The College of Saint Rose CIS 433 – Programming Languages David Goldschmidt, Ph.D. Regular expressions{week 06} from Concepts of Programming Languages, 9th edition by Robert W. Sebesta, Addison-Wesley, 2010, ISBN 0-13-607347-6
Regular expressions (i) • A regular expression is an expression ina “mini language” designed specificallyfor textual pattern matching • Support for regular expressions are availablein many languages, including Java, JavaScript,C, C++, PHP, etc.
Regular expressions (ii) • A pattern contains numerous character groupings and is specified as a string • Patterns to match a phone number include: • [0-9][0-9][0-9]−[0-9][0-9][0-9]−[0-9][0-9][0-9][0-9] • [0-9]{3}−[0-9]{3}−[0-9]{4} • \d\d\d−\d\d\d−\d\d\d\d • \d{3}−\d{3}−\d{4} • (\d\d\d) \d\d\d−\d\d\d\d
Regular expressions in Java (i) • The String class in Java provides a pattern matching method called matches(): • Unlike other languages, Java requires the pattern to match the entire string String s = "Pattern matching in Java!"; String p = "\\w+\\s\\w+\\s\\w{2}\\s\\w+!"; if ( s.matches( p ) ) { System.out.println( "MATCH!" ); }
Regular expressions in Java (ii) • Additional pattern-matching methods: • Use the replaceFirst() and replaceAll() methods to replace a pattern with a string: String s = "<title>Cool Web Site</title>"; String p = "</?\w+>"; String result = s.replaceAll( p, "" );