
package uk.co.wingpath.util;

import java.util.*;
import java.util.regex.*;

/**
* This class performs string re-writes using a {@link Pattern} to match
* a string, and a {@link Formatter format} to construct the new string.
* <p>In the format string "%1$s" can be used to refer to the whole input
* string, "%2$s" to refer to the first parenthesized capturing group, and so on.
*/
public class Substituter
{
    private final Pattern pattern;
    private final String format;

    /**
    * Constructs a {@code Substituter} using the supplied pattern and format.
    * @param pattern the pattern.
    * @param format the format.
    */
    public Substituter (Pattern pattern, String format)
    {
        this.pattern = pattern;
        this.format = format;
    }

    /**
    * Constructs a {@code Substituter} using the supplied pattern and format.
    * @param pattern the pattern.
    * @param format the format.
    */
    public Substituter (String pattern, String format)
    {
        this.pattern = Pattern.compile (pattern);
        this.format = format;
    }

    /**
    * Performs substitutions on the supplied string.
    * @param str the string to re-written.
    * @return the re-written string, or {@code null} if the supplied string
    * did not match the pattern.
    */
    public String substitute (String str)
    {
        Matcher m = pattern.matcher (str);
        if (!m.matches ())
            return null;
        int n = m.groupCount () + 1;
        Object [] args = new String [n];

        for (int i = 0 ; i < n ; i++)
        {
            args [i] = m.group (i);
        }

        return String.format (format, args);
    }
}

