Java Regex to Check if String is Number
You can use Java regular expressions to check if a string is a number. Here is an example code:
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String str1 = "12345"; // 数字
String str2 = "12.34"; // 小数
String str3 = "abc123"; // 包含字母
String str4 = "12a34"; // 包含非数字字符
System.out.println(isNumeric(str1)); // true
System.out.println(isNumeric(str2)); // true
System.out.println(isNumeric(str3)); // false
System.out.println(isNumeric(str4)); // false
}
public static boolean isNumeric(String str) {
Pattern pattern = Pattern.compile("-?\\d+(\\.\\d+)?"); // 数字的正则表达式
return pattern.matcher(str).matches();
}
}
In the code above, the isNumeric method takes a string parameter and uses a regular expression to determine if the string is a number. The regular expression -?\d+(\.\d+)? represents an optional negative sign, followed by one or more digits, and optionally followed by a decimal point and one or more digits. The Pattern.compile method is used to create a pattern for the regular expression, then the matcher method is used to apply this pattern to the string. Finally, the matches method is used to determine if the string matches the pattern, returning true if it does and false if it doesn’t.