Home
Categories
Dictionary
Download
Project Details
Changes Log
FAQ
License

util.regex


    1  RegexCollection
       1.1  Algorithm
       1.2  RegexMatcher result
       1.3  Examples

The regex package contains additional classes which work with the Java regex package.

RegexCollection

The RegexCollection class allows to specify a list of regex patterns and match a CharSequence against all the patterns. It simplifies the usage of several regex expressions against the same input.

Algorithm

The class iterate from the first specified pattern to the last one:
  • If a pattern match, the iteration stops and the associated RegexMatcher will be returned
  • If the last pattern does not match, the iteration stops on the associated RegexMatcher

RegexMatcher result

The RegexMatcher class encapsulates a java.util.regex.Matcher. The main methods of this class are: This class encapsulates a lot of methods of the Matcher class. For example:
   RegexMatcher matcher = collection.matcher("156");
   String group = matcher.group(2);
is equivalent to:
   RegexMatcher matcher = collection.matcher("156");
   String group = matcher.getMatcher().group(2);

Examples

The first example shows a simple usage of the class:
   RegexCollection collection = new RegexCollection();
   collection.addPattern("number", "\\d+");
   collection.addPattern("letters", "[A-Za-z]+");
      
   RegexMatcher matcher = collection.matcher("156");
   String name = matcher.getPatternName(); // return "number"
   boolean matches = matcher.matches(); // return true

   matcher = collection.matcher("Slayer");
   name = matcher.getPatternName(); // return "letters"
   matches = matcher.matches(); // return true

   matcher = collection.matcher("1349 band");
   name = matcher.getPatternName(); // return "letters"
   matches = matcher.matches(); // return false      
This second example shows how you can use the class with a switch case:
   RegexCollection collection = new RegexCollection();
   collection.addPattern("number", "\\d+");
   collection.addPattern("letters", "[A-Za-z]+");
   collection.addPattern("bother", "[A-Za-z]+ \\d+");
      
   RegexMatcher matcher = collection.matcher("156");
   if (matcher.matches()) {
      switch (matcher.getPatternName()) {
        case "number":
             System.out.println("This is a number";
             break;
        case "letters":
             System.out.println("This is a word";
             break;      
        case "both":
             System.out.println("This is a word followed by a number";
             break;        
      }
   }     

Categories: packages | util

Copyright 2006-2024 Herve Girod. All Rights Reserved. Documentation and source under the LGPL v2 and Apache 2.0 licences