Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert String to appropriate DataType

Tags:

java

string

date

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.

like image 608
Nick Avatar asked Feb 08 '13 10:02

Nick


People also ask

How do I change a string type?

Changing any data type into a String Any built-in data type can be converted into its string representation by the str() function. Built-in data type in python include:- int , float , complex , list , tuple , dict etc.

How do you convert string to in Python?

In Python an integer can be converted into a string using the built-in str() function. The str() function takes in any python data type and converts it into a string. But use of the str() is not the only way to do so. This type of conversion can also be done using the “%s” keyword, the .

Can you convert a string to an int?

One effective way to convert a string object into a numeral int is to use the stoi() function. This method is commonly used for newer versions of C++, with is being introduced with C++11. It takes as input a string value and returns as output the integer version of it.


1 Answers

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;
}
like image 186
Mikhail Vladimirov Avatar answered Sep 19 '22 01:09

Mikhail Vladimirov