Tutorialspoint examples

Learn java tutorial with examples for beginners online

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.

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

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.tutorialspointexamples;
 
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
Download tutorialspointexamples Android App
Copyright © 2018 Tutorialspoint examples DMCA.com Protection Status