regular expression and escaping

Posted by pstanton on Stack Overflow See other posts from Stack Overflow or by pstanton
Published on 2010-03-15T04:31:33Z Indexed on 2010/03/15 4:39 UTC
Read the original article Hit count: 248

Filed under:
|

Sorry if this has been asked, my search brought up many off topic posts.

I'm trying to convert wildcards from a user defined search string (wildcard is "*") to postgresql like wildcard "%".

I'd like to handle escaping so that "%" => "\%" and "\*" => "*"

I know i could replace \* with something else prior to replacing * and then swap it back, but i'd prefer not to and instead only convert * using a pattern that selects it when not proceeded by \.

String convertWildcard(String like)
{
    like = like.replaceAll("%", "\\%");
    like = like.replaceAll("\\*", "%");
    return like;
}

Assert.assertEquals("%", convertWildcard("*"));
Assert.assertEquals("\%", convertWildcard("%"));
Assert.assertEquals("*", convertWildcard("\*")); // FAIL

Assert.assertEquals("a%b", convertWildcard("a*b"));
Assert.assertEquals("a\%b", convertWildcard("a%b"));
Assert.assertEquals("a*b", convertWildcard("a\*b")); // FAIL

ideas welcome.

© Stack Overflow or respective owner

Related posts about java

Related posts about regex