info@tutsfinder.in



Regular Expression

Regular Expression is an API that is used to defining String patterns that we want to match to strings.

Java provides java.util.Regex package for pattern matching .

We can perform such tasks –

• String matching with validation criteria.

• Data Extraction


Package consists of 3 classes Pattern, Matcher and PatternSyntaxException.

1. Pattern – It defines the patterns that you want to search.

2. Matcher – It is used for performing matching operations of pattern(the string you have entered).

3. PatternSyntaxException – It indicates exceptions in Regular Expression Pattern. And package also consist of 1 Interface..

MatchResultInterface

Hold the results of a successful match of a Pattern against a given String.



A simple program of regex.

  
import java.util.regex.Pattern;
public class RegexExample {  
    
public static void main(String args[]) { 
  
      System.out.println(Pattern.matches("...s", "tuts"));
  
      System.out.println(Pattern.matches(".i...", "finder"));  
   
	  System.out.println(Pattern.matches("tuts......", "tutsfinder"));
  
    }

}
	


Output:
true
false
true


Matching Symbols

These are used to match the characters in the specefied string.



Regular Expression


Meta Character

Meta characters have predefined meanings. They works as short code.



Regular Expression


Quantifiers

Quantifiers define how many times an element can occur.



Regular Expression


In this Program we have used matching symbols, meta characters and quantifiers.

  
import java.util.regex.*;  

class RegexExampleMain{
  
public static void main(String args[]){  
	
	System.out.println(Pattern.matches("[6789]{1}[0-9]{9}", "9897654321"));//true  
	System.out.println(Pattern.matches("[6789][0-9]{9}", "523164987"));//false starts from 5
   
	System.out.println(Pattern.matches("[tuts]?", "t"));//true t comes only one time 
	System.out.println(Pattern.matches("[tuts]+", "t"));//true  once or more times

	System.out.println(Pattern.matches("[tuts]", "s"));//true (only from t, u, s)

	System.out.println(Pattern.matches("\\d", "tuts"));//false (\d only used for digits)  
	System.out.println(Pattern.matches("\\d", "1"));//true  
	}
}