Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

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(); 
}

Wednesday, 12 June 2013

Map with Case-Insensitive Keys

Below is the easy way, for case-insensitive key searches in a Map.


Map<String, String[]> treemap = new TreeMap<String, String[]>(String.CASE_INSENSITIVE_ORDER);

treemap.put("name1","value1");
treemap.put("NAME2","value2");
 
treemap.get("NAME1")   //you get "value1"
treemap.get("naME2")   //you get "value2"



[WARNING]  treemap.get(null) throws NulllPointerException in certain versions of Java