使用Java正则表达式接受日期字符串(MM-dd-yyyy格式)吗?

使用java正则表达式接受日期字符串(mm-dd-yyyy格式)吗?

以下是匹配 dd-MM-yyyy 格式日期的正则表达式

^(1[0-2]|0[1-9])/(3[01]|[12][0-9]|0[1-9])/[0-9]{4}$

登录后复制

匹配该格式字符串中的日期。

编译上面的compile()方法的表达式Pattern 类。

绕过所需的输入字符串作为 Pattern 类的 matcher() 方法的参数来获取 Matcher 对象。

立即学习“Java免费学习笔记(深入)”;

如果匹配发生,Matcher 类的 matches() 方法返回 true,否则返回 false。因此,调用此方法来验证数据。

示例 1

<!–

现场演示

–>

import java.util.regex.Matcher;import java.util.regex.Pattern;public class MatchingDate {   public static void main(String[] args) {      String date = "01/12/2019";      String regex = "^(1[0-2]|0[1-9])/(3[01]|[12][0-9]|0[1-9])/[0-9]{4}$";      //Creating a pattern object      Pattern pattern = Pattern.compile(regex);      //Matching the compiled pattern in the String      Matcher matcher = pattern.matcher(date);      boolean bool = matcher.matches();      if(bool) {         System.out.println("Date is valid");      } else {         System.out.println("Date is not valid");      }   }}

登录后复制

输出

Date is valid

登录后复制

String 类的 matches() 方法接受正则表达式并将当前字符串与之匹配,如果匹配则返回 true,否则返回 false。因此,要验证给定日期(字符串格式)是否符合所需格式 –

获取日期字符串。调用 matches( ) 方法,将上述正则表达式作为参数传递给它。

示例 2

<!–

现场演示

–>

import java.util.Scanner;public class Just {   public static void main(String[] args) {      Scanner sc = new Scanner(System.in);      System.out.println("Enter your name: ");      String name = sc.nextLine();      System.out.println("Enter your Date of birth: ");      String dob = sc.nextLine();      //Regular expression to accept date in MM-DD-YYY format      String regex = "^(1[0-2]|0[1-9])/(3[01]|[12][0-9]|0[1-9])/[0-9]{4}$";      boolean result = dob.matches(regex);      if(result) {         System.out.println("Given date of birth is valid");      } else {         System.out.println("Given date of birth is not valid");      }   }}

登录后复制

输出1

Enter your name:JanakiEnter your Date of birth:26/09/1989Given date of birth is not valid

登录后复制

输出 2

Enter your name:JanakiEnter your Date of birth:09/26/1989Given date of birth is valid

登录后复制

以上就是使用Java正则表达式接受日期字符串(MM-dd-yyyy格式)吗?的详细内容,更多请关注【创想鸟】其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。

发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/3046262.html

(0)
上一篇 2025年3月13日 16:53:02
下一篇 2025年2月18日 00:38:13

AD推荐 黄金广告位招租... 更多推荐

相关推荐

发表回复

登录后才能评论