Presentation is loading. Please wait.

Presentation is loading. Please wait.

Portions adapted with permission from the textbook author. CS-1020 Dr. Mark L. Hornick 1 Regular Expressions and String processing Animated Version.

Similar presentations


Presentation on theme: "Portions adapted with permission from the textbook author. CS-1020 Dr. Mark L. Hornick 1 Regular Expressions and String processing Animated Version."— Presentation transcript:

1 Portions adapted with permission from the textbook author. CS-1020 Dr. Mark L. Hornick 1 Regular Expressions and String processing Animated Version

2 Portions adapted with permission from the textbook author. CS-1020 Dr. Mark L. Hornick 2 Useful String methods MethodMeaning compareToCompares the two strings lexicographically. int result = str1.compareTo( str2 ) substringExtracts the a substring from a string. String s2 = str1.substring( 1, 4 ) trimRemoves the leading and trailing spaces. str1.trim( ) concatConcatenates the specified string to the end of this string. String str3 = str1.concat( str2 ) equalsCompares the two strings (case-sensitive). boolean isSame = str1.equals( str2 ) equalsIgnoreCase Compares the two strings (case-insensitive). boolean isSame = str1.equalsIgnoreCase( str2 )

3 Portions adapted with permission from the textbook author. CS-1020 Dr. Mark L. Hornick 3 What if we want to identify specific characters in a String? MethodMeaning startsWith Returns true if a string starts with a specified prefix string. boolean hasPrefix = str1.startsWith( str2 ) endsWith Returns true if a string ends with a specified suffix string. boolean hasSuffix = str1.endsWith( str2 ) contains Returns true if a string contains the specified string. boolean hasContent = str1.contains( str2 )

4 Portions adapted with permission from the textbook author. CS-1020 Dr. Mark L. Hornick 4 More powerful methods MethodMeaning replaceAll Replaces all characters in the string that match the regular expression. String str3 = str1.replaceAll( regex, c ) matches Returns true if a string matches the specified regular expression. boolean matches = str1.matches( str2 )

5 Portions adapted with permission from the textbook author. CS-1020 Dr. Mark L. Hornick 5 Regular Expression Examples Regular Expression StringDescription [aeiou] A single character a, e, i, o, or u. [0-9][0-9] Any two-digit number from 00 to 99. [0-9&&[^4567]] A single digit that is 0, 1, 2, 3, 8, or 9. [a-z0-9] A single character that is either a lowercase letter or a digit. [a-zA-z][a-zA-Z0-9_$]* A valid Java identifier consisting of alphanumeric characters, underscores, and dollar signs, with the first character being an alphabetical character. [wb](ad|eed) Matches wad, weed, bad, and beed. (AZ|CA|CO)[0-9][0-9] Matches AZxx, CAxx, and COxx, where x is a single digit. See book pp 502-509

6 Portions adapted with permission from the textbook author. CS-1020 Dr. Mark L. Hornick 6 Rules of Regular Expressions The brackets [ ] represent choices An asterisk symbol * means zero or more occurrences. A plus symbol + means one or more occurrences. A hat symbol ^ means negation. A hyphen – means ranges. A parentheses ( ) and a vertical bar | mean a range of choices for multiple characters.

7 Portions adapted with permission from the textbook author. CS-1020 Dr. Mark L. Hornick 7 The matches() method uses Regular Expressions If str and regex are String objects: bool doesMatch = str.matches(regex);

8 Portions adapted with permission from the textbook author. CS-1020 Dr. Mark L. Hornick 8 The replaceAll() method replaces all occurrences of a substring that matches a given regular expression with a given replacement string. String originalText, modifiedText; originalText = “Hello there” modifiedText = originalText.replaceAll("[aeiou]","@"); // resulting string is “H@ll@ th@r@” Pattern: Replace all vowels with the symbol @

9 Portions adapted with permission from the textbook author. CS-1020 Dr. Mark L. Hornick 9 The Pattern and Matcher Classes The matches and replaceAll methods of the String class are shorthand for using the Pattern and Matcher classes from the java.util.regex package. The previous example: bool doesMatch = str.matches(regex); is equivalent to Pattern p = Pattern.compile(regex); Matcher m = p.matcher(str); bool doesMatch = m.matches();

10 Portions adapted with permission from the textbook author. CS-1020 Dr. Mark L. Hornick 10 What is the compile method? Converts the stated regular expression to an internal format to carry out the pattern-matching operation much more quickly. When using the matches method, the conversion is done every time. so it is more efficient to use the compile method when a search for the same pattern is needed multiple times.

11 Portions adapted with permission from the textbook author. CS-1020 Dr. Mark L. Hornick 11 The find Method The find method is another powerful method of the Matcher class. It searches for the next sequence in a string that matches the pattern, and returns true if the pattern is found. When a matcher finds a matching sequence of characters, we can query the location of the sequence by using the start and end methods.

12 Portions adapted with permission from the textbook author. CS-1020 Dr. Mark L. Hornick 12 Immutable Strings In Java a String object is immutable Once a String object is created, it cannot be changed, It is not possible to replace a character with another character, or to remove a character The String methods seen so far do not change the original string. A new string is created from the original. substring() creates a new string from a given string. The String class is defined in this manner for efficiency.

13 Portions adapted with permission from the textbook author. CS-1020 Dr. Mark L. Hornick 13 Effect of Immutability We can do this because String objects are immutable.

14 Portions adapted with permission from the textbook author. CS-1020 Dr. Mark L. Hornick 14 The StringBuilder Class In many string processing applications, it is necessary to change the contents of a string. i.e. it needs to be mutable The StringBuilder class is used for manipulating the contents of a string replacing a character, appending a string with another string, deleting a portion of a string

15 Portions adapted with permission from the textbook author. CS-1020 Dr. Mark L. Hornick 15 StringBuilder Example StringBuilder word = new StringBuilder("Java"); word.setCharAt(0, 'D'); word.setCharAt(1, 'i'); Changing a string Java to Diva word : StringBuilder Java Before word : StringBuilder Diva After word.setCharAt(0, 'D'); word.setCharAt(1, 'i');

16 Portions adapted with permission from the textbook author. CS-1020 Dr. Mark L. Hornick 16 Sample Processing Replace all vowels in the sentence with ‘X’. char letter; String inSentence = JOptionPane.showInputDialog(null, "Sentence:"); StringBuilder tempStringBuffer = new StringBuilder(inSentence); int numberOfCharacters = tempStringBuffer.length(); for (int index = 0; index < numberOfCharacters; index++) { letter = tempStringBuffer.charAt(index); if (letter == 'a' || letter == 'A' || letter == 'e' || letter == 'E' || letter == 'i' || letter == 'I' || letter == 'o' || letter == 'O' || letter == 'u' || letter == 'U' ) { tempStringBuffer.setCharAt(index,'X'); } JOptionPane.showMessageDialog(null, tempStringBuffer );

17 Portions adapted with permission from the textbook author. CS-1020 Dr. Mark L. Hornick 17 append and insert methods append is used to append a String or StringBuilder object to the end of a StringBuilder object. The method can also take an argument of the primitive data type. Any primitive data type argument is converted to a string before it is appended to a StringBuilder object. A string can be inserted at a specified position by using the insert method.


Download ppt "Portions adapted with permission from the textbook author. CS-1020 Dr. Mark L. Hornick 1 Regular Expressions and String processing Animated Version."

Similar presentations


Ads by Google