java - 判断字符串内容的类型
迷茫
迷茫 2017-04-18 10:04:51
0
2
660
迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all(2)
PHPzhong

Currently all I can think of is regular judgment

阿神

Assume that the data type is limited to 8 basic types + String.
The numerical types are divided into integers and floating point numbers;
Boolean values ​​and character types are easier to judge;
Regular expressions for integers: ^-?[1-9]d*$^-?[1-9]d*$
浮点数的正则表达式:^[-]?[1-9]d*.d*|-0.d*[1-9]d*$For floating point numbers Regular expression: ^[-]?[1-9]d*.d*|-0.d*[1-9]d*$
The value of 0 needs to be judged separately. This comparison Simple, write it yourself.

public static final String CHAR_PATTERN = "[^0-9]";
public static final String INT_PATTERN = "^-?[1-9]\d*$";
public static final String DOUBLE_PATTERN = "^[-]?[1-9]\d*\.\d*|-0\.\d*[1-9]\d*$";

public static Object convert(String item) {
    // 忽略所有空字符串或全是空格的字符串
    if (!StringUtils.hasText(item)) {
        return null;
    }
    item = item.trim();
    if ("true".equalsIgnoreCase(item) || "false".equalsIgnoreCase(item)) {
        return Boolean.valueOf(item);
    }
    if (item.matches(CHAR_PATTERN)) {
        return Character.toString(item);
    }
    if (item.matches(INT_PATTERN)) {
        return Integer.valueOf(item);
    }
    if (item.matches(DOUBLE_PATTERN)) {
        return Double.valueOf(item);
    }
    return item;
}

The above code is typed by hand and may be written incorrectly.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!