“正则表达式 练习:验证是否整数或小数”的版本间的差异

来自姬鸿昌的知识库
跳到导航 跳到搜索
(建立内容为“https://www.bilibili.com/video/BV1Eq4y1E79W?p=25”的新页面)
 
第1行: 第1行:
 
https://www.bilibili.com/video/BV1Eq4y1E79W?p=25
 
https://www.bilibili.com/video/BV1Eq4y1E79W?p=25
 +
 +
要考虑正数和负数,比如:123、-345、34.89、-87.9、-0.01、0.45等
 +
 +
=== 我的实现 ===
 +
<syntaxhighlight lang="java">
 +
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));
 +
        }
 +
 +
    }
 +
 +
}
 +
</syntaxhighlight>
 +
 +
=== 视频里的实现 ===
 +
<syntaxhighlight lang="console">
 +
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));
 +
        }
 +
 +
    }
 +
 +
}
 +
</syntaxhighlight>

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));
        }

    }

}