Nick
Nick

Reputation: 1277

Convert String to appropriate DataType

I have a String that could be in many different formats. I need to be able to recognize the actual type of the value at runtime and then transform the value to that type.

For example. If I have a String Fri Feb 08 07:30:00 GMT 2013 this is actually a Date and a the String should be transformed into a date object and returned as such.

My current solution to this problem is to 'try' to convert it to a data type, if the conversion succeeds then all is good, if the conversion fails then move on to the next conversion attempt. This works, but is ugly and un-maintainable and I'm sure a better solution already exists out there.

Thanks.

Upvotes: 5

Views: 4584

Answers (4)

Mikhail Vladimirov
Mikhail Vladimirov

Reputation: 13900

You may use separate regular expression for each data type like this:

private final static Pattern DATE_PATTERN = 
    Pattern.compile (
        "(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat) " + 
        "(?:Jan|Feb|Mar|Apr|May|June?|July?|Aug|Sept?|Oct|Nov|Dec) " + 
        "\\d\\d \\d\\d:\\d\\d:\\d\\d \\S+ \\d\\d\\d\\d");

private final static Pattern DOUBLE_PATTERN = 
    Pattern.compile (
        "[\\+\\-]?\\d+\\.\\d+(?:[eE][\\+\\-]?\\d+)?");

private final static Pattern INTEGER_PATTERN = 
    Pattern.compile (
        "[\\+\\-]?\\d+");

public static Object stringToObject (String string)
{
    if (DATE_PATTERN.matcher (string).matches ())
        return stringToDate (string);
    else if (DOUBLE_PATTERN.matcher (string).matches ())
        return Double.valueOf (string);
    else if (INTEGER_PATTERN.matcher (string).matches ())
        return Integer.valueOf (string);
    else return string;
}

Upvotes: 4

SpaceTrucker
SpaceTrucker

Reputation: 13556

Your approach is fine, if the strings passed to you are out of your control. Just one more suggestion: You should apply every possible conversion and check for ambiguous strings. If multiple conversions succeed then the string is ambiguous and you should do some error handling, probably throwing an exception.

Upvotes: 0

mustaphahawi
mustaphahawi

Reputation: 297

public static void main(String[] args) {

    String s = "Fri Feb 08 07:30:00 GMT 2013";
    SimpleDateFormat FT = new SimpleDateFormat("EEE MMM dd hh:mm:ss z yyyy");
    Date d;
    try {
        d = FT.parse(s);
        System.out.println(d);
    } catch (ParseException ex) {
        Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
    }
}

Upvotes: 1

Chedy2149
Chedy2149

Reputation: 3061

Try regular expression : You can write a pattern for each data type you have, then match that pattern with each actual string you can associate a conversion for each match. Here is a simple example (in pseudo Java):

String name = "Mike"; // This is an English name
String nameRegEx ="[A-Z][a-z]+"; //this patterns matches an english name
Matcher nameMatcher = new Matcher(regEx);
if (match.matches(name)){// I use the matches() method to verify the format of the string
    Name nameObject = Converter.getNameObjectFromString(name);//I make the conversion
}

Checkout the java documentation for more details on matchers and regular expressions : http://docs.oracle.com/javase/tutorial/essential/regex/

Upvotes: 0

Related Questions