正则表达式 练习:验证是否整数或小数
Jihongchang(讨论 | 贡献)2022年11月22日 (二) 07:24的版本
https://www.bilibili.com/video/BV1Eq4y1E79W?p=25
要考虑正数和负数,比如:123、-345、34.89、-87.9、-0.01、0.45等
我的实现
public class Homework02 {
public static void main(String[] args) {
String regex = "^-?\\d+\\.?\\d*$";
String[] contents = {"123", "-345", "34.89", "-87.9", "-0.01", "0.45", "--123", "-0.123", "abc"};
for (String content:contents) {
System.out.printf("\"%s\".matches(regex):%b \n", content, content.matches(regex));
}
}
}
视频里的实现
public class Homework02 {
public static void main(String[] args) {
String regex = "^[-+]?\\d+(\\.\\d+)?$";
String[] contents = {"123", "-345", "34.89", "-87.9", "-0.01", "0.45", "--123", "-0.123", "abc"};
for (String content:contents) {
System.out.printf("\"%s\".matches(regex):%b \n", content, content.matches(regex));
}
}
}