Download presentation
Presentation is loading. Please wait.
Published byEvelyn McBride Modified over 9 years ago
1
The College of Saint Rose CIS 433 – Programming Languages David Goldschmidt, Ph.D. from Concepts of Programming Languages, 9th edition by Robert W. Sebesta, Addison-Wesley, 2010, ISBN 0-13-607347-6
2
A regular expression is an expression in a “mini language” designed specifically for textual pattern matching Support for regular expressions are available in many languages, including Java, JavaScript, C, C++, PHP, etc.
3
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
4
regular expressionmatchesexample xyzspecified characters xyzJava matches Java.any single characterJava matches J..a [xyz]single character x, y, or zJava matches Ja[uvwx]a [^xyz]any character except x, y, or zJava matches Ja[^abcd]a [a-z]any character a through zJava matches [A-M]a[t-z]a [^a-z]any character except a through zJava matches Jav[^b-x] [A-Za-z]any “word” characterJava matches Jav[a-fp-z] \dany digit character [0-9]1234 matches \d\d\d\d \Dany non-digit character [^0-9]Java matches \D\D\D\D \wany “word” character [A-Za-z]Java matches \wava \Wany non-word character [^A-Za-z]2+3 matches \d\W\d \sany whitespace characterD G matches \w\s\w \Sany non-whitespace characterD + matches \S\s\S
5
regular expressionmatchesexample ^the beginning of the stringJava matches ^Java $the end of the stringJava matches Java$ pattern*zero or more occurrences of patternJAVA matches [A-Z]* pattern+one or more occurrences of patternJava matches J[a-z]+ pattern?zero or one occurrence of pattern−50 matches −?\d+ pattern{n}exactly n occurrences of patternJava matches \w{4} pattern{n,m}between n and m (inclusive) occurrences of pattern Java matches \w{3,8} pattern{n,}at least n occurrences of patternJava matches \w{3}
6
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!" ); }
7
Additional pattern-matching methods: Use the replaceFirst() and replaceAll() methods to replace a pattern with a string: String s = " Cool Web Site "; String p = " "; String result = s.replaceAll( p, "" );
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.