Java Reference
In-Depth Information
// Note that we have to use \\ because we need a literal \
// and Java uses a single \ as an escape character
String pStr = "\\d" ; // A numeric digit
String text = "Apollo 13" ;
Pattern p = Pattern . compile ( pStr );
Matcher m = p . matcher ( text );
System . out . print ( pStr + " matches " + text + "? " + m . find ());
System . out . println ( " ; match: " + m . group ());
pStr = "[a..zA..Z]" ; //Any letter
p = Pattern . compile ( pStr );
m = p . matcher ( text );
System . out . print ( pStr + " matches " + text + "? " + m . find ());
System . out . println ( " ; match: " + m . group ());
// Any number of letters, which must all be in the range 'a' to 'j'
// but can be upper- or lowercase
pStr = "([a..jA..J]*)" ;
p = Pattern . compile ( pStr );
m = p . matcher ( text );
System . out . print ( pStr + " matches " + text + "? " + m . find ());
System . out . println ( " ; match: " + m . group ());
text = "abacab" ;
pStr = "a....b" ; // 'a' followed by any four characters, followed by 'b'
p = Pattern . compile ( pStr );
m = p . matcher ( text );
System . out . print ( pStr + " matches " + text + "? " + m . find ());
System . out . println ( " ; match: " + m . group ());
Let's conclude our quick tour of regular expressions by meeting a new method that
was added to Pattern as part of Java 8: asPredicate() . This method is present to
allow us to easily bridge from regular expressions to the Java Collections and their
new support for lambda expressions.
For example, suppose we have a regex and a collection of strings. It's very natural to
ask the question: “Which strings match against the regex?” We do this by using the
filter idiom, and by converting the regex to a Predicate using the helper method,
like this:
String pStr = "\\d" ; // A numeric digit
Pattern p = Pattern . compile ( pStr );
String [] inputs = { "Cat" , "Dog" , "Ice-9" , "99 Luftballoons" };
List < String > ls = Arrays . asList ( inputs );
List < String > containDigits = ls . stream ()
. filter ( p . asPredicate ())
. collect ( Collectors . toList ());
System . out . println ( containDigits );
Search WWH ::




Custom Search