“正则表达式 练习:验证是否整数或小数”的版本间的差异
跳到导航
跳到搜索
Jihongchang(讨论 | 贡献) (→视频里的实现) |
Jihongchang(讨论 | 贡献) (→视频里的实现) |
||
第39行: | 第39行: | ||
public static void main(String[] args) { | public static void main(String[] args) { | ||
− | String regex = "^[-+]?\\d | + | String regex = "^[-+]?(0|[1-9]\\d*)(\\.\\d+)?$"; |
− | String[] contents = {"123", "-345", "34.89", "-87.9", "-0.01", "0.45", "--123", "-0.123", "abc"}; | + | String[] contents = {"123", "-345", "34.89", "-87.9", "-0.01", "0.45", "--123", "-0.123", "abc", "0.89", "01.89"}; |
for (String content:contents) { | for (String content:contents) { | ||
第50行: | 第50行: | ||
} | } | ||
+ | </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 | ||
+ | "0.89".matches(regex):true | ||
+ | "01.89".matches(regex):false | ||
</syntaxhighlight> | </syntaxhighlight> |
2022年11月22日 (二) 07:32的最新版本
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