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.
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.
The above code is typed by hand and may be written incorrectly.