Given a string, the task is to find the appropriate data type using regular expressions in Java.
In general, we can divide all data types into the following types:
Note: Character inputs and boolean values also will be considered as string.
Examples:
Input: “56.73” Output: java.lang.Double Explanation: 56.73 is of float data type which are part of java.lang.Double Input: “true” Output: java.lang.String Explanation: Here true is considered as a regular string which is a part of java.lang.String
Approach:
Below is the implementation of the above approach:
public class GFG { // method stub public static void main(String[] arg) { String input = "56.73"; String dataType = null; // checking for Integer if (input.matches("\\d+")) { dataType = "java.lang.Integer"; } // checking for floating point numbers else if (input.matches("\\d*[.]\\d+")) { dataType = "java.lang.Double"; } // checking for date format dd/mm/yyyy else if (input.matches( "\\d{2}[/]\\d{2}[/]\\d{4}")) { dataType = "java.util.Date"; } // checking for date format mm/dd/yyyy else if (input.matches( "\\d{2}[/]\\d{2}[/]\\d{4}")) { dataType = "java.util.Date"; } // checking for date format dd-mon-yy else if (input.matches( "\\d{2}[-]\\w{3}[-]\\d{2}")) { dataType = "java.util.Date"; } // checking for date format dd-mon-yyyy else if (input.matches( "\\d{2}[-]\\w{3}[-]\\d{4}")) { dataType = "java.util.Date"; } // checking for date format dd-month-yy else if (input.matches("\\d{2}[-]\\w+[-]\\d{2}")) { dataType = "java.util.Date"; } // checking for date format dd-month-yyyy else if (input.matches("\\d{2}[-]\\w+[-]\\d{4}")) { dataType = "java.util.Date"; } // checking for date format yyyy-mm-dd else if (input.matches( "\\d{4}[-]\\d{2}[-]\\d{2}")) { dataType = "java.util.Date"; } // checking for String else { dataType = "java.lang.String"; } System.out.println("The datatype of " + input + " is: " + dataType); } }
Output
The datatype of 56.73 is: java.lang.Double
Australia
UK
UAE
Singapore
Canada
New
Zealand
Malaysia
USA
India
South
Africa
Ireland
Saudi
Arab
Qatar
Kuwait
Hongkong
Copyright 2016-2023 www.programmingshark.com - All Rights Reserved.
Disclaimer : Any type of help and guidance service given by us is just for reference purpose. We never ask any of our clients to submit our solution guide as it is, anywhere.