Reply to comment

Validate Input in Java using Regular Expression

Tagged:  
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Validate {

	public static void main(String[] args) {

		Scanner input = new Scanner(System.in);
		
		Boolean isValid = false;

		while( ! isValid ){
			String expression = "(Y|N)";

			Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);

			System.out.print("Are you sure you want to exit the program now? (Y/N)\t:");
			String gender = input.next();

			Matcher matcher = pattern.matcher(gender);
			isValid = matcher.matches();

			if( isValid )
				break;
		}
	}

}

Reply

The content of this field is kept private and will not be shown publicly.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
1 + 2 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.