Showing posts with label Pattern. Show all posts
Showing posts with label Pattern. Show all posts

Using Java RegEx Pattern and Matcher

Using pattern matcher in java is very easy and simple to identify a specific word or text from the given input String. Also we can check for case insensitive formats also by using Java RegEx. In that case lets see simple example for finding specific text from the multiple String inputs and return whether given text or (Pattern) matches from the given input.
Using Java RegEx Pattern and Matcher

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PatternMatcherTest {

 public static void main(String[] args) {
  String str = "The listener interface for receiving text events. " +
    "The class that is interested in processing a text event implements this interface. " +
    "The object created with that class is then registered with a component using the " +
    "component's addTextListener method. When the component's text changes, " +
    "the listener object's textValueChanged method is invoked.";
  PatternMatcherTest obj = new PatternMatcherTest();
  System.out.println("PRESENT : "+obj.checkPatternMatch(str, "interface"));
  System.out.println("PRESENT : "+obj.checkPatternMatch(str, "EVENTS"));
  System.out.println("PRESENT : "+obj.checkPatternMatch(str, "Java"));
  System.out.println("PRESENT : "+obj.checkPatternMatch(str, "Method"));

 public boolean checkPatternMatch(String str, String regex) {
  Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
  Matcher match = pattern.matcher(str);
  if (match.find())
   return true;
   return false;


PRESENT : true
PRESENT : true
PRESENT : false
PRESENT : true