The CharMatcher class determines a true or false value for any Java char value, just as Predicate does for any Object.
Sr.No | Methods & Description |
---|---|
1 | CharMatcher and(CharMatcher other)Returns a matcher that matches any character matched by both this matcher and other. |
2 | static CharMatcher anyOf(CharSequence sequence)Returns a char matcher that matches any character present in the given character sequence. |
3 | boolean apply(Character character)Deprecated. Provided only to satisfy the Predicate interface; use matches(char) instead. |
4 | String collapseFrom(CharSequence sequence, char replacement)Returns a string copy of the input character sequence, with each group of consecutive characters that match this matcher replaced by a single replacement character. |
5 | int countIn(CharSequence sequence)Returns the number of matching characters found in a character sequence. |
6 | static CharMatcher forPredicate(Predicate<? super Character> predicate)Returns a matcher with identical behavior to the given Character-based predicate, but which operates on primitive char instances instead. |
7 | int indexIn(CharSequence sequence)Returns the index of the first matching character in a character sequence, or -1 if no matching character is present. |
Create the following java program using any editor of your choice in say C:/> Guava.
Example
Following is the GuavaTester.java code −
import com.google.common.base.CharMatcher; import com.google.common.base.Splitter; public class GuavaTester { public static void main(String args[]) { GuavaTester tester = new GuavaTester(); tester.testCharMatcher(); } private void testCharMatcher() { System.out.println(CharMatcher.DIGIT.retainFrom("mahesh123")); // only the digits System.out.println(CharMatcher.WHITESPACE.trimAndCollapseFrom(" Mahesh Parashar ", ' ')); // trim whitespace at ends, and replace/collapse whitespace into single spaces System.out.println(CharMatcher.JAVA_DIGIT.replaceFrom("mahesh123", "*")); // star out all digits System.out.println(CharMatcher.JAVA_DIGIT.or(CharMatcher.JAVA_LOWER_CASE).retainFrom("mahesh123")); // eliminate all characters that aren't digits or lowercase } }
Compile the class using javac compiler as follows
C:\Guava>javac GuavaTester.java
Now run the GuavaTester to see the result −
C:\Guava>java GuavaTester
Output
This will produce the following output −
123 Mahesh Parashar mahesh*** mahesh123