Presentation is loading. Please wait.

Presentation is loading. Please wait.

An Introduction to Regular Expressions Specifying a Pattern that a String must meet.

Similar presentations


Presentation on theme: "An Introduction to Regular Expressions Specifying a Pattern that a String must meet."— Presentation transcript:

1 An Introduction to Regular Expressions Specifying a Pattern that a String must meet

2 Character Specifiers "ABC" - The literal characters A, B, C. The String must contain the substring "ABC". "[ABC]" - Logical OR. The String must contain either an 'A', a 'B' or a 'C'. "[A-Za-z] - A range of characters. String must contain any upper- or lower-case alphabetic character. "[^def] - Negation. Any character except d, e, or f.

3 Character Specifiers "[0-9&&[^46]]" - Combining range and negation. Specifies any numeric digit except a '4' or a '6'.

4 Predefined Character Classes "\d" - Any digit ("[0-9]") "\D" - Any non-digit ("[^0-9]") "\s" - A white-space character. "\S" - A non-white-space character. "\w" - A "word" character ("A-Za-z_0-9") "\W" - a non-word character

5 Repetition {n} - Exactly this number of repetitions. "[0-9]{9}" - Exactly 9 numeric digits. {n 1,n 2 } - A range of repetitions. "[A-Z]{5,7}" - Between 5 and 7 upper- case alphabetic characters. + - One or more. "[A-Za-z]+" - One or more alphabetic characters. * - Zero or more. "[12345]* - Zero or more instances of the digits 1, 2, 3, 4, or 5.

6 Using Regex to Validate Input The String class contains a non-static "matches" method that takes a String regex as a parameter and returns a boolean. if( ssn.matches("[0-9]{9}" )

7 Regex Examples String productID = JOptionPane.showInputDialog( null, "Enter Product ID:" ); if( productID != null ) { //If the Product ID contains 2 or 3 alpha //chars, followed by 4 or 5 numeric chars. if(productID.matches("[A-Za-z]{2,3}[0-9]{4,5}") //Product ID is valid. else //Product ID is not valid. }

8 Regex Examples String regex = "[0-9]{10}"; String phone = JOptionPane.showInputDialog( null, "Enter patient's phone number:" ); if( phone != null ) { if( phone.matches( regex ) … } String regex = "[2-9][0-9]{2}[2-9][0-9]{6}"


Download ppt "An Introduction to Regular Expressions Specifying a Pattern that a String must meet."

Similar presentations


Ads by Google