“正则表达式 练习:验证是否整数或小数”的版本间的差异
跳到导航
跳到搜索
Jihongchang(讨论 | 贡献) |
Jihongchang(讨论 | 贡献) (→视频里的实现) |
||
第20行: | 第20行: | ||
} | } | ||
+ | </syntaxhighlight><syntaxhighlight lang="console"> | ||
+ | "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 | ||
</syntaxhighlight> | </syntaxhighlight> | ||
+ | |||
=== 视频里的实现 === | === 视频里的实现 === | ||
− | <syntaxhighlight lang=" | + | <syntaxhighlight lang="java"> |
public class Homework02 { | public class Homework02 { | ||
2022年11月22日 (二) 07:25的版本
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 = "^[-+]?\\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));
}
}
}