Java String Escape escapeRegexpSymbol(String expr)

Here you can find the source of escapeRegexpSymbol(String expr)

Description

The method compiles specified string to convert special symbol of regular expression, it avoids the special char in string is parsed as regular symbol.

License

Open Source License

Parameter

Parameter Description
expr a parameter

Declaration

private static String escapeRegexpSymbol(String expr) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2004 Actuate Corporation.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors://from w  ww  . j  a  v a2s  . com
 *  Actuate Corporation  - initial API and implementation
 *******************************************************************************/

import java.util.ArrayList;

import java.util.List;

public class Main {
    /**
     * The method compiles specified string to convert special symbol of regular
     * expression, it avoids the special char in string is parsed as regular
     * symbol.
     * 
     * @param expr
     * @return
     * @since 2.3.1
     */
    private static String escapeRegexpSymbol(String expr) {
        char[] specialSymbol = new char[] { '$', '(', ')', '*', '+', '.', '[', '?', '^', '{', '|', '}', '\\' };

        List<Character> specialList = new ArrayList<Character>();
        for (int i = 0; i < specialSymbol.length; i++) {
            specialList.add(Character.valueOf(specialSymbol[i]));
        }

        StringBuffer sb = new StringBuffer(expr);
        for (int i = 0; i < sb.length(); i++) {
            int index = specialList.indexOf(Character.valueOf(sb.charAt(i)));
            if (index < 0) {
                continue;
            }
            if (specialList.get(index).charValue() == '\\') {
                sb.insert(i++, '\\');
                sb.insert(i++, '\\');
            }
            sb.insert(i++, '\\');
        }
        return sb.toString();
    }
}

Related

  1. escapeJavaStyleString(StringBuilder out, String str, boolean escapeSingleQuote, boolean escapeForwardSlash)
  2. escapeQuotes(String string)
  3. escapeRegex(String regex)
  4. escapeRegexChars(String str, char... ignores)
  5. escapeRegexp(final String str)
  6. escapeReservedWord(String input)
  7. escapeSelected(String str, String chars)
  8. escapeSolr(String value)
  9. escapeToFileName(String name)