Tuesday, March 16, 2010

Java and Regular Expressions

So the other day I was working away with some open source bits and was needing to do some string parsing. I am a hugh fan of regular expressions. They are vary efficient; and once understood, make it vary easy to perform complex string parsing with very few lines of code. I was trying to perform matching on special regular expressions characters; namely '?.' I was trying to escape the ? with black slashes. In the java world you have to use two black slashes for every one that you want. So '\\' turns into '\' and '\\\\' translate into '\\.' After spending a while trying to escape the ? I found a very simple solution. Just add the "Pattern.LITERAL" flag to the Pattern constructor. Here's an example:

Pattern pattern = Pattern.compile(name,Pattern.CASE_INSENSITIVE | Pattern.LITERAL);

Happy coding...

No comments:

Post a Comment