Convert String to corresponding DataType

I have Stringone that can be in many different formats. I need to be able to recognize the actual type of a value in runtime, and then convert the value to that type.

For instance. If I have String Fri Feb 08 07:30:00 GMT 2013, it is in fact Date, but Stringshould be converted to date objectand returned as such.

My current solution to this problem is to "try" to convert it to a data type, if the conversion is successful, then all is well, if the conversion fails, go to the next conversion attempt. It works, but is ugly and insecure, and I am sure that a better solution already exists there.

Thank.

+5
source share
4 answers

You can use a separate regular expression for each data type, for example:

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;
}
+4
source
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);
    }
}
+1
source

: , , , . ( -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
}

java : http://docs.oracle.com/javase/tutorial/essential/regex/

0

Your approach is great if the lines passed to you are uncontrollable. Another suggestion: you should apply all possible conversions and check for ambiguous strings. If multiple conversions succeed, the string is ambiguous, and you should do some error handling, possibly throwing an exception.

0
source

All Articles