CodesJava

Easy learning with example program codes

java regex pattern validate html tag


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 html tag pattern

<("[^"]*"|'[^']*'|[^'">])*>

This regular expression refers to a pattern which start with an opening tag “<" , follow by double quotes "string", or single quotes 'string' but does not allow one double quotes (") "string, one single quote (') 'string or a closing tag > without single or double quotes enclosed. At last, end with a closing tag “>”

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 = 
			"<("[^"]*"|'[^']*'|[^'">])*>";
	public static void main(String args[]){ 
		List<String> values = new ArrayList<String>();	
		values.add("<br>"); 
		values.add("<input/>"); 
		values.add("<input value=> >");
 
		Pattern pattern = Pattern.compile(PATTERN);
		for (String value : values){
		  Matcher matcher = pattern.matcher(value);
		  if(matcher.matches()){
			  System.out.println("Tag "+ value +" is valid");
		  }else{
			  System.out.println("Tag "+ value +" is invalid");
		  }		  
		}
	}
}

Output

Tag <br> is valid
Tag <input/> is valid
Tag <input value=> > is invalid
Sign Up/ Sign In
Ask a Question


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