Created
March 2, 2009 05:56
-
-
Save javajosh/72635 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* | |
* Ray Tayek needs function that escapes all regular expression characters in a string. | |
*/ | |
public class RegexEscape { | |
private static char[] reserved="$()*+-.?[\\]^{|}".toCharArray(); | |
//the toCharArray() way | |
public static String encode(String arg){ | |
char[] source = arg.toCharArray(); | |
char[] target = new char[source.length *2]; //worst case we have to escape everything | |
int target_index = 0; | |
for (char c : source) { | |
for (char r : reserved) { | |
if (c == r) { | |
target[target_index++] = '\\'; | |
break; | |
} | |
} | |
target[target_index++] = c; | |
} | |
return new String(target, 0, target_index); | |
} | |
//just a testing main | |
public static void main(String args[]){ | |
//visual inspection to make sure it works. expect: fi \\ fi\{\}\+fo fum\^ | |
System.out.println(encode("fi \\ fi{}+fo fum^")); | |
//now a simple profile | |
long start = System.currentTimeMillis(); | |
for (int i=0; i<100000; i++){ | |
encode("fi \\ fi{}+fo fum^"); | |
} | |
long stop = System.currentTimeMillis(); | |
System.out.println((stop - start) + "ms"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment