KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > mockobjects > constraint > Matches


1 /*
2  * Copyright (c) 2002 Nat Pryce. All rights reserved.
3  *
4  * Created on February 10, 2002, 11:35 PM
5  */

6 package com.mockobjects.constraint;
7
8 import java.util.regex.Matcher JavaDoc;
9 import java.util.regex.Pattern JavaDoc;
10
11
12 /**
13  * Is the value a string that matches a regular expression?
14  */

15 public class Matches implements Constraint {
16     private Pattern JavaDoc _pattern;
17
18     /** Creates a new Matches predicate.
19      *
20      * @param regex
21      * A regular expression string used to create a
22      * {@link java.util.regex.Pattern}. The {@link #eval} method
23      * returns true when applied to Strings that match this pattern.
24      * Matching is tested by calling the
25      * {@link java.util.regex.Matcher#matches} method of a
26      * {@link java.util.regex.Matcher} object.
27      */

28     public Matches(String JavaDoc regex) {
29         _pattern = Pattern.compile(regex);
30     }
31
32     public boolean eval(Object JavaDoc arg) {
33         if (arg instanceof String JavaDoc) {
34             Matcher JavaDoc matcher = _pattern.matcher((String JavaDoc) arg);
35             return matcher.matches();
36         } else {
37             return false;
38         }
39     }
40
41     public String JavaDoc toString() {
42         return "a string that matches <" + _pattern.toString() + ">";
43     }
44 }
45
Popular Tags