正则表达式 练习:验证是否整数或小数
跳到导航
跳到搜索
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));
}
}
}
"123".matches(regex):true
"-345".matches(regex):true
"34.89".matches(regex):true
"-87.9".matches(regex):true
"-0.01".matches(regex):true
"0.45".matches(regex):true
"--123".matches(regex):false
"-0.123".matches(regex):true
"abc".matches(regex):false
视频里的实现
public class Homework02 {
public static void main(String[] args) {
String regex = "^[-+]?(0|[1-9]\\d*)(\\.\\d+)?$";
String[] contents = {"123", "-345", "34.89", "-87.9", "-0.01", "0.45", "--123", "-0.123", "abc", "0.89", "01.89"};
for (String content:contents) {
System.out.printf("\"%s\".matches(regex):%b \n", content, content.matches(regex));
}
}
}
"123".matches(regex):true
"-345".matches(regex):true
"34.89".matches(regex):true
"-87.9".matches(regex):true
"-0.01".matches(regex):true
"0.45".matches(regex):true
"--123".matches(regex):false
"-0.123".matches(regex):true
"abc".matches(regex):false
"0.89".matches(regex):true
"01.89".matches(regex):false