[cp-patches] [PATCH] Implement Pattern.quote() API method

Pekka Enberg penberg at kernel.org
Sat Jan 22 19:38:05 UTC 2011


From: Ivan Maidanski <ivmai at mail.ru>

2010-07-02  Ivan Maidanski  <ivmai at mail.ru>

	* java/util/regex/Pattern.java:
	(quote): Implement new 1.5 Java API method.
---
 ChangeLog                    |    5 +++++
 java/util/regex/Pattern.java |   37 ++++++++++++++++++++++++++++++++++++-
 2 files changed, 41 insertions(+), 1 deletions(-)

diff --git a/ChangeLog b/ChangeLog
index 4d0bf6d..52b4760 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,3 +1,8 @@
+2010-07-02  Ivan Maidanski  <ivmai at mail.ru>
+
+	* java/util/regex/Pattern.java:
+	(quote): Implement new 1.5 Java API method.
+
 2011-01-21  Pekka Enberg <penberg at kernel.org>
 
 	* java/lang/Class.java:
diff --git a/java/util/regex/Pattern.java b/java/util/regex/Pattern.java
index 7d1fc84..2aae9bb 100644
--- a/java/util/regex/Pattern.java
+++ b/java/util/regex/Pattern.java
@@ -1,5 +1,6 @@
 /* Pattern.java -- Compiled regular expression ready to be applied.
-   Copyright (C) 2002, 2004, 2005, 2007 Free Software Foundation, Inc.
+   Copyright (C) 2002, 2004, 2005, 2007, 2010
+   Free Software Foundation, Inc.
 
 This file is part of GNU Classpath.
 
@@ -37,6 +38,8 @@ exception statement from your version. */
 
 package java.util.regex;
 
+import gnu.java.lang.CPStringBuilder;
+
 import gnu.java.util.regex.RE;
 import gnu.java.util.regex.REException;
 import gnu.java.util.regex.RESyntax;
@@ -260,6 +263,38 @@ public final class Pattern implements Serializable
   }
 
   /**
+   * Returns a literal pattern for the specified String.
+   *
+   * @since 1.5
+   */
+  public static String quote(String str)
+  {
+    int eInd = str.indexOf("\\E");
+    if (eInd < 0)
+      {
+        // No need to handle backslashes.
+        return "\\Q" + str + "\\E";
+      }
+
+    CPStringBuilder sb = new CPStringBuilder(str.length() + 16);
+    sb.append("\\Q"); // start quote
+    
+    int pos = 0;
+    do
+      {
+        // A backslash is quoted by another backslash;
+        // 'E' is not needed to be quoted.
+        sb.append(str.substring(pos, eInd))
+          .append("\\E" + "\\\\" + "E" + "\\Q");
+        pos = eInd + 2;
+      } while ((eInd = str.indexOf("\\E", pos)) >= 0);
+
+    sb.append(str.substring(pos, str.length()))
+      .append("\\E"); // end quote
+    return sb.toString();
+  }
+
+  /**
    * Return the regular expression used to construct this object.
    * @specnote Prior to JDK 1.5 this method had a different behavior
    * @since 1.5
-- 
1.7.1




More information about the Classpath-patches mailing list