Thursday, 26 September 2013

Java: Code to unquote string using Regex


str="\"hello\"" // or "'hello'"

public static unquote(String str)
{
        str = str.trim();
if (str.startsWith("'") && str.endsWith("'"))
{
    str = match(str, "(?<=').*(?=')");
}
else if (str.startsWith("\"") && str.endsWith("\""))
{
         str = match(str, "(?<=\").*(?=\")");
}
}

//matches the pattern
private static String match(final String string, final String regex)
{
final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(string);
matcher.find();
return matcher.group(); 
}

No comments:

Post a Comment