CodesJava

Easy learning with example program codes

java regex pattern validate 12 hours format


Regular expressions

Regular expressions represents a sequence of symbols and characters expressing a string or pattern to be searched for within a longer piece of text. The abbreviation for regular expression is regex. In programming regular expressions are mainly used to define constraint on strings like password, email validation.

Regular expression time in 12 hours format pattern

(1[012]|[1-9]):[0-5][0-9](\s)?(?i)(am|pm)

This regular expression refers to a pattern which start from 0-12, then a semi colon (:) and follow by 00-59, and end with am or pm.

Example

package com.codesjava;
 
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
public class RegexTest {
	private static final String PATTERN = 
			"(1[012]|[1-9]):[0-5][0-9](\s)?(?i)(am|pm)";
	public static void main(String args[]){ 
		List<String> values = new ArrayList<String>();	
		values.add("3:00 am"); 
		values.add("5:00 PM"); 
		values.add("23:00 am");
		values.add("01:00 pm");
 
		Pattern pattern = Pattern.compile(PATTERN);
		for (String value : values){
		  Matcher matcher = pattern.matcher(value);
		  if(matcher.matches()){
			  System.out.println("Time "+ value +" is valid 12Hours Format");
		  }else{
			  System.out.println("Time "+ value +" is invalid 12Hours Format");
		  }		  
		}
	}
}

Output

Time 3:00 am is valid 12Hours Format
Time 5:00 PM is valid 12Hours Format
Time 23:00 am is invalid 12Hours Format
Time 01:00 pm is invalid 12Hours Format
Sign Up/ Sign In
Ask a Question


Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki