Java Programing laungage

java.util Projects

java.util Project 1

Greedy and Non-Greedy Matching
Previous Home Next
adplus-dvertising

Greedy Matching

This is the way of matching the two string from one to another. In this method, the matcher method is used to return that word of the complete content of the file or the string or text in which all the characters of the search string is found.

Non-Greedy Matching

This is also a way of the string matching, In this way of the matching, string is searched in the complete string or text inputted by the user or the contents of the file. if any character of the searched string is found in the complete string or text in which another one is searched. In this way of matching, the matcher returns all the words or character from the whole string or text where from no any characters are fond in the string or text which is not present in the searched string or text.

Code Description

"a.+?c"

This is the regular expression which is used in the following program for the Non-Greedy search or matching from the given string or the content of the file.

"a.*c"

This is also a regular expression of java programming language which performs the Greedy search or matching from the given string or the content of the file.

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 matchingtest {
public static void main(String[] args) throws IOException{
 BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
 System.out.print("Enter string/text in which search operation will be performed: ");
 String str = br.readLine();
 //  Non-Greedy Matching.
 Pattern pat = Pattern.compile("a.+?c");
 Matcher match = pat.matcher(str);
 String str1 = match.replaceAll("F");
 System.out.println(str1);
 //  Greedy Matching.
 pat = Pattern.compile("a.*c");
 match = pat.matcher(str);
 str1 = match.replaceAll("z");
 System.out.println(str);
 System.out.println(str1);
 }
}

Previous Home Next