Java String Quote quoteLiteralAsRegexp(String text)

Here you can find the source of quoteLiteralAsRegexp(String text)

Description

quote Literal As Regexp

License

Open Source License

Declaration

public static String quoteLiteralAsRegexp(String text) 

Method Source Code

//package com.java2s;

public class Main {
    public static String quoteLiteralAsRegexp(String text) {
        final int end = text.length();

        StringBuilder sb = new StringBuilder(end + 8);

        for (int i = 0; i < end;) {
            char c = text.charAt(i++);

            switch (c) {
            case ' ': // one of few special cases: collate, collapse into "one or more" style regexp
            case '\t':
                while ((i < end) && text.charAt(i) <= ' ') {
                    ++i;/* w w w  .j  a v  a 2s  . c  om*/
                }
                sb.append("[ \t]+");
                break;

            case '.':
                sb.append("\\.");
                break;

            // Looks like we need to match not just open, but close parenthesis; probably same for others
            case '(':
            case ')':
            case '[':
            case ']':
            case '\\':
            case '{':
            case '}':
            case '|':
            case '*':
            case '?':
            case '+':
            case '$':
            case '^':
                // Automaton has heartburn with less-than
            case '<':
            case '>':
                // as well as with quoted entries (how about single quotes?)
            case '"':
                // and some other operators
            case '&':
                sb.append('\\');
                sb.append(c);
                break;

            default:
                sb.append(c);
            }
        }
        return sb.toString();
    }
}

Related

  1. quoteJava(String s)
  2. quoteJavascriptString(String s)
  3. quoteJavaString(String s)
  4. quoteJavaString(String s)
  5. quoteJsonLib(String string)
  6. quoteLocation(String location)
  7. quoteMdxIdentifier(String ident)
  8. quoteMe(String unquoted)
  9. quoteMeta(String s)