Java String Quote quoteMeta(String s)

Here you can find the source of quoteMeta(String s)

Description

Quote all regular expression meta characters in s, in order to search for s literally.

License

Open Source License

Declaration

public static String quoteMeta(String s) 

Method Source Code

//package com.java2s;
/*//from  ww w  .  ja v  a2 s.com
 Copyright (C) 2003 Morten O. Alver
    
 All programs in this directory and
 subdirectories are published under the GNU General Public License as
 described below.
    
 This program is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation; either version 2 of the License, or (at
 your option) any later version.
    
 This program is distributed in the hope that it will be useful, but
 WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 General Public License for more details.
    
 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
 USA
    
 Further information about the GNU GPL is available at:
 http://www.gnu.org/copyleft/gpl.ja.html
    
 */

public class Main {
    /**
     * Quote all regular expression meta characters in s, in order to search for
     * s literally.
     */
    public static String quoteMeta(String s) {
        // work around a bug: trailing backslashes have to be quoted
        // individually
        int i = s.length() - 1;
        StringBuffer bs = new StringBuffer("");
        while ((i >= 0) && (s.charAt(i) == '\\')) {
            --i;
            bs.append("\\\\");
        }
        s = s.substring(0, i + 1);
        return "\\Q" + s.replaceAll("\\\\E", "\\\\E\\\\\\\\E\\\\Q") + "\\E" + bs.toString();
    }
}

Related

  1. quoteJsonLib(String string)
  2. quoteLiteralAsRegexp(String text)
  3. quoteLocation(String location)
  4. quoteMdxIdentifier(String ident)
  5. quoteMe(String unquoted)
  6. quotemeta(String s)
  7. quoteMonetDbIdentifier(String ident)
  8. quoteMonetDbValue(String value)
  9. quoteNameIfNecessary(String name)