以下是匹配 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 对象。
如果匹配发生,matcher 类的 matches() 方法返回 true,否则返回 false。因此,调用此方法来验证数据。
示例 1import 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( ) 方法,将上述正则表达式作为参数传递给它。示例 2import 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"); } }}
输出1enter your name:janakienter your date of birth:26/09/1989given date of birth is not valid
输出 2enter your name:janakienter your date of birth:09/26/1989given date of birth is valid
以上就是使用java正则表达式接受日期字符串(mm-dd-yyyy格式)吗?的详细内容。