90 likes | 109 Views
An Introduction to Regular Expressions. Specifying a Pattern that a String must meet. "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'.
E N D
An Introduction to Regular Expressions Specifying a Pattern that a String must meet
"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. Character Specifiers
"[0-9&&[^46]]" - Combining range and negation. Specifies any numeric digit except a '4' or a '6'. Character Specifiers
"\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 Predefined Character Classes
{n} - Exactly this number of repetitions. "[0-9]{9}" - Exactly 9 numeric digits. • {n1,n2} - 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. Repetition
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}" ) Using Regex to Validate Input
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. } 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}" Regex Examples