title: Escaping special characters in Java Regular Expressions
body: <p>Is there any method in Java or any open source library for escaping (not quoting) a special character (meta-character), in order to use it as a regular expression?</p>
  
  <p>This would be very handy in dynamically building a regular expression, without having to manually escape each individual character.</p>
  
  <p>For example, consider a simple regex like <code>\d+\.\d+</code> that matches numbers with a decimal point like <code>1.2</code>, as well as the following code:</p>
  
  <pre><code>String digit = "d";
  String point = ".";
  String regex1 = "\\d+\\.\\d+";
  String regex2 = Pattern.quote(digit + "+" + point + digit + "+");
  
  Pattern numbers1 = Pattern.compile(regex1);
  Pattern numbers2 = Pattern.compile(regex2);
  
  System.out.println("Regex 1: " + regex1);
  
  if (numbers1.matcher("1.2").matches()) {
      System.out.println("\tMatch");
  } else {
      System.out.println("\tNo match");
  }
  
  System.out.println("Regex 2: " + regex2);
  
  if (numbers2.matcher("1.2").matches()) {
      System.out.println("\tMatch");
  } else {
      System.out.println("\tNo match");
  }
  </code></pre>
  
  <p>Not surprisingly, the output produced by the above code is:</p>
  
  <pre><code>Regex 1: \d+\.\d+
      Match
  Regex 2: \Qd+.d+\E
      No match
  </code></pre>
  
  <p>That is, <code>regex1</code> matches <code>1.2</code> but <code>regex2</code> (which is "dynamically" built) does not (instead, it matches the literal string <code>d+.d+</code>).</p>
  
  <p>So, is there a method that would automatically escape each regex meta-character?</p>
  
  <p>If there were, let's say, a static <code>escape()</code> method in <code>java.util.regex.Pattern</code>, the output of</p>
  
  <pre><code>Pattern.escape('.')
  </code></pre>
  
  <p>would be the string <code>"\."</code>, but </p>
  
  <pre><code>Pattern.escape(',')
  </code></pre>
  
  <p>should just produce <code>","</code>, since it is not a meta-character. Similarly,</p>
  
  <pre><code>Pattern.escape('d')
  </code></pre>
  
  <p>could produce <code>"\d"</code>, since <code>'d'</code> is used to denote digits (although escaping may not make sense in this case, as <code>'d'</code> could mean literal <code>'d'</code>, which wouldn't be misunderstood by the regex interpeter to be something else, as would be the case with <code>'.'</code>).</p>