Dear All,

I have written a RegexpFilter, which I would like to contribute if you
find that it is of any use. Below you will find the source snippet. If
you will agree, that I'll commit it.

Cheers,

Krzysztof


/**
 * This filter uses regexp to create expressions and allow
 * you to do replace on those expressions. 
 *
 * This filter works like the Perl subst function. Given a 
 * regular expression of "a*b", a String to substituteIn of 
 * "aaaabfooaaabgarplyaaabwackyb" and the substitution String "-", the 
 * resulting String returned by process(..) would be
"-foo-garply-wacky-".
 *
 * <pre><code>
 *    Filter filter = new RegexpFilter();
 *    filter.addAttribute("a*b","-");
 *    String text = "aaaabfooaaabgarplyaaabwackyb";
 *    String result = filter.process(text);
 *    System.out.println(result);
 * </code></pre>
 *
 * Produces: -foo-garply-wacky-
 *
 * @author <a href="mailto:[EMAIL PROTECTED]">K.
Zelazowski</a>
 * @version 1.0
 */
public class RegexpFilter extends Hashtable implements Filter {
    
    public RegexpFilter() 
    {
        super(4);
    }

    /** Returns the name of the filter */
    public String getInfo() 
    {
        return "RegexpFilter";
    }

    /**
     * This method actually performs the filtering.
     */
    public String process(String to_process) 
    {
        if ( to_process == null || to_process.length() == 0 )
            return "";
 
        String substituteIn = to_process;
        Enumeration enum = keys();

        while (enum.hasMoreElements()) {
            RE r = (RE)enum.nextElement();
            String substitution = (String)get(r);
            substituteIn = r.subst(substituteIn, substitution);
        }
        return substituteIn;
    }

    /**
     *  Add regular expression - substitution pair.
     */
    public Filter addAttribute(String expression,Object substitution) 
    {
        try {
            RE r = new RE(expression);
            put(r, substitution);
        }
        catch (RESyntaxException e) {
            return null;
        }

        return(this);
    }

    /**
     * Get rid of the specified expression-substitution pair.
     */
    public Filter removeAttribute(String expression) 
    {
        try
        {
             RE r = new RE(expression);
             remove(r);
        }
        catch(Exception e)
        { 
        }
        return(this);
    }

    /**
     * Does the filter contains this expression? 
     */
    public boolean hasAttribute(String expression) 
    {
        try {
            RE r = new RE(expression);
            return containsKey(r);
        }
        catch (Exception e) {
        }
        return false;
    }
}


--
------------------------------------------------------------
To subscribe:        [EMAIL PROTECTED]
To unsubscribe:      [EMAIL PROTECTED]
Archives and Other:  <http://java.apache.org/main/mail.html>
Problems?:           [EMAIL PROTECTED]

Reply via email to