Java - Write code to Convert the string into a regex to allow easy matching.

Requirements

Write code to Convert the string into a regex to allow easy matching.

Demo

//package com.book2s;

public class Main {
    public static void main(String[] argv) {
        String param = "$%^&*book2s.com";
        System.out.println(toRegex(param));
    }/*ww w . ja  v a 2  s  . c  o m*/

    /**
     * Convert the string into a regex to allow easy matching.  In both S3 and EC2 regex strings
     * are used for matching.  We must remember to quote all special regex characters that appear 
     * in the string.
     */
    public static String toRegex(String param) {
        StringBuffer regex = new StringBuffer();
        for (int i = 0; i < param.length(); i++) {
            char next = param.charAt(i);
            if ('*' == next)
                regex.append(".+"); // -> multi-character match wild card
            else if ('?' == next)
                regex.append("."); // -> single-character match wild card
            else if ('.' == next)
                regex.append("\\."); // all of these are special regex characters we are quoting
            else if ('+' == next)
                regex.append("\\+");
            else if ('$' == next)
                regex.append("\\$");
            else if ('\\' == next)
                regex.append("\\\\");
            else if ('[' == next)
                regex.append("\\[");
            else if (']' == next)
                regex.append("\\]");
            else if ('{' == next)
                regex.append("\\{");
            else if ('}' == next)
                regex.append("\\}");
            else if ('(' == next)
                regex.append("\\(");
            else if (')' == next)
                regex.append("\\)");
            else if ('&' == next)
                regex.append("\\&");
            else if ('^' == next)
                regex.append("\\^");
            else if ('-' == next)
                regex.append("\\-");
            else if ('|' == next)
                regex.append("\\|");
            else
                regex.append(next);
        }

        return regex.toString();
    }
}

Related Exercise