import org.json.JSONException; import org.json.JSONObject; import org.dom4j.DocumentException; import org.dom4j.DocumentHelper; public class StringTest { /** * @param args */ public static void main(String[] args) { String string1 = "123"; String string2 = "fdgsewe323"; String string3 = "{/"task/":/"324vfsdfg/"}"; String string4 = "<ww>3243</ww>"; // System.out.println("string1::number"+isNumber(string1)); // System.out.println("string2::number"+isNumber(string2)); // System.out.println("string3::json"+isJson(string3)); // System.out.println("string4::xml"+isXML(string4)); // System.out.println("string1::json"+isJson(string1)); // System.out.println("string2::xml"+isXML(string2)); // System.out.println("string3::number"+isNumber(string3)); // System.out.println("string4::xml"+isXML(string4)); System.out.println("string1::"+getType(string1)); System.out.println("string2::"+getType(string2)); System.out.println("string3::"+getType(string3)); System.out.println("string4::"+getType(string4)); } public static String getType(String string) { if (isNumber(string)) return "Number"; else if (isJson(string)) return "Json"; else if (isXML(string)) return "xml"; else return "String"; } /** * 推断字符串是否是数字 */ public static boolean isNumber(String value) { return isInteger(value) || isDouble(value); } /** * 推断字符串是否是整数 */ public static boolean isInteger(String value) { try { Integer.parseInt(value); return true; } catch (NumberFormatException e) { return false; } } /** * 推断字符串是否是浮点数 */ public static boolean isDouble(String value) { try { Double.parseDouble(value); if (value.contains(".")) return true; return false; } catch (NumberFormatException e) { return false; } } /** * 推断是否是json结构 */ public static boolean isJson(String value) { try { new JSONObject(value); } catch (JSONException e) { return false; } return true; } /** * 推断是否是xml结构 */ public static boolean isXML(String value) { try { DocumentHelper.parseText(value); } catch (DocumentException e) { return false; } return true; } }