Java String escape for regex pattern

Description

Java String escape for regex pattern


//package com.demo2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        String s = "demo2s.com()*&^%$";
        System.out.println(escapeRegex(s));
    }//from   ww w. j a  v a 2s  .  c o m

    /**
     * Escapes the special characters from a string so it can be used as part of
     * a regex pattern. This method is for use on gnu.regexp style regular
     * expressions.
     */
    public static String escapeRegex(String s) {
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            // Test if c is an escapable character
            if ("()|*+?.{}[]$^\\".indexOf(c) != -1) {
                sb.append('\\');
                sb.append(c);
            } else {
                sb.append(c);
            }
        }

        return sb.toString();
    }

}



PreviousNext

Related