Java Programing laungage

java.util Projects

java.util Project 1

Regular Expression Search
Previous Home Next

Regular Expression

It is used to perform many string related operations. This is the way of manipulate different type of operations like Editing, search and manipulating string. Its all can be performed by the regular expression. It has both type characters like literal and meta characters. In this page of the tutorials we shall be learn how to search a string from the given string exactly.

Program Description

This example gives us the search facility in which it takes two string or text. One text is searched in another one text or string and tells you for the occurrence of the given string for searching into a long string. If the string does not lies in the given string from which the string has to be searched.

Code Description

Pattern

This is the class of the java.util.regex package which is the compiled representation. In this method the firstly that string is compiled which is Specified string into an instance of this class. The pattern to be used to create a matcher object which finds the character sequences for the regular expression.

Matcher

This is also a class of java.util.regex package which is used to match character sequences.

matcher.find()

This method is used to find the matched string in the given string for searching. This method returns a Boolean value either true or false.

Example


package r4r;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class expressionsearch {
public static void main(String[] args) throws IOException{
 BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
 System.out.print("Enter string in which we have to search: ");
 String str = br.readLine();
 System.out.print("Enter character to search: ");
 String str1 = br.readLine();
  Pattern pattern = Pattern.compile(str1);
 Matcher matcher = pattern.matcher(str);
 int a = 0;
 while(matcher.find()){
 a = a + 1;
 }
 if(a == 0)
 System.out.println("String is not found.");
 else
 System.out.println("Occurrence of the String is: " + a);
 }
}

Previous Home Next