1 / 8

An Introduction to Regular Expressions

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'.

tposton
Download Presentation

An Introduction to Regular Expressions

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

  2. "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

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

  4. "\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

  5. {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

  6. 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

  7. 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

  8. 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

More Related