Java Regex Create toRegex(String param)

Here you can find the source of toRegex(String param)

Description

Convert the string into a regex to allow easy matching.

License

Apache License

Declaration

public static String toRegex(String param) 

Method Source Code

//package com.java2s;
// Licensed to the Apache Software Foundation (ASF) under one

public class Main {
    /**//from   w w w  . j a  va  2s.  c om
     * 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

  1. toRegex(String includes)
  2. toRegEx(String input)
  3. toRegex(String name)
  4. toRegex(String wildcard)
  5. toRegExFormat(String pattern)
  6. toRegexPattern(String filter)
  7. toRegexPattern(String pattern)