Register Now

Login

Lost Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Login

Register Now

Welcome to All Test Answers

regular expressions using Java

you are going to create a small programs. In writing this program, you will practice regex in Java.
Prompt the user to enter a date in DD/MM/YY or DD-MM-YY format. Once the user inputs something and hits enter, check to see if the entry matched the expected format. You MUST use regular expressions (aka regex) to perform this check. A single regular expression check is all this must take. Finally, as output, declare whether the input was a valid or invalid date.
Examples:
Program: That is an invalid date.
Program: Enter a date in DD/MM/YY or DD-MM-YY format:
User: 46-03/97
Program: That is an invalid date.
Program: Enter a date in DD/MM/YY or DD-MM-YY format:
User: 46-03-97
Program: That is an invalid date.
Program: Enter a date in DD/MM/YY or DD-MM-YY format:
User: 30-12-19
Program: That is a valid date.
Program: Enter a date in DD/MM/YY or DD-MM-YY format:
User: 12345678
Program: That is an invalid date.
Program: Enter a date in DD/MM/YY or DD-MM-YY format:
User: 26/12/17
Program: That is a valid date.
Program: Enter a date in DD/MM/YY or DD-MM-YY format:
User: 12-13-26

Answer:

import java.util.*;
public class assign2_2 {
	
	public static void main(String[] args) {
		
		String input; 												
		String checkDate = "(0[1-9]|1\\d|2\\d|3[0-1])(/|-)(0\\d|1[0-2])(/|-)(\\d\\d|0\\d|1[0-3])";
		
		System.out.print("Enter a date in DD/MM/YY or DD-MM-YY format: ");
		Scanner keyboard = new Scanner(System.in); 
		input = keyboard.nextLine();

		if(input.matches(checkDate)){
			System.out.println("That is a valid date ");
		}
		
		else{
			System.out.println("That is an invalid date ");
		}
		
	}
}

About

Leave a reply

Captcha Click on image to update the captcha .

error: Content is protected !!