/*
 * Copyright (c) 2002 Nat Pryce. All rights reserved.
 *
 * Created on February 10, 2002, 11:35 PM
 */
package com.mockobjects.constraint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * Is the value a string that matches a regular expression?
 */
public class Matches implements Constraint {
    private Pattern _pattern;

    /** Creates a new Matches predicate.
     *
     *  @param regex
     *      A regular expression string used to create a
     *      {@link java.util.regex.Pattern}.  The {@link #eval} method
     *      returns true when applied to Strings that match this pattern.
     *      Matching is tested by calling the
     *      {@link java.util.regex.Matcher#matches} method of a
     *      {@link java.util.regex.Matcher} object.
     */
    public Matches(String regex) {
        _pattern = Pattern.compile(regex);
    }

    public boolean eval(Object arg) {
        if (arg instanceof String) {
            Matcher matcher = _pattern.matcher((String) arg);
            return matcher.matches();
        } else {
            return false;
        }
    }

    public String toString() {
        return "a string that matches <" + _pattern.toString() + ">";
    }
}
