Java 正则表达式如何判断是否为闰年

发布时间:2025-01-23 19:08:38 作者:小樊
来源:亿速云 阅读:92

要使用 Java 正则表达式判断一个年份是否为闰年,首先需要了解闰年的规则:

  1. 如果年份能被 4 整除,但不能被 100 整除,则为闰年。
  2. 如果年份能被 400 整除,则为闰年。

以下是一个 Java 代码示例,使用正则表达式判断一个年份是否为闰年:

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class LeapYear {
    public static void main(String[] args) {
        String year = "2020"; // 更改这个值来测试其他年份
        boolean isLeap = isLeapYear(year);
        System.out.println(year + (isLeap ? " 是" : " 不是") + "闰年");
    }

    public static boolean isLeapYear(String year) {
        String regex = "^(19|20)\\d\\d$"; // 正则表达式匹配 1900-2099 年间的年份
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(year);

        if (!matcher.matches()) {
            return false; // 不在 1900-2099 年间,无法判断闰年
        }

        int y = Integer.parseInt(year);
        return (y % 4 == 0 && y % 100 != 0) || (y % 400 == 0);
    }
}

这个示例首先使用正则表达式 ^(19|20)\\d\\d$ 匹配 1900-2099 年间的年份。然后,根据闰年规则判断匹配到的年份是否为闰年。

推荐阅读:
  1. java用正则表达式判断字符串是否为数字的方法
  2. java用正则表达式判断是否是小数的方法

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java

上一篇:如何通过正则表达式提取日期

下一篇:如何利用正则表达式实现密码复杂性检查

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》