Posts which you will also like.

Monday, January 14, 2013

Using Regular Expressions in Java



In this java tutorial we will learn to use regular expression in java.Regular expression is very powerful tool for text manipulation and searching.It provides the fastest searching in huge amount of available data.So if you know it definitely you will save a lot time while doing these operations.In this tutorial I am going to describe how to use regular expression in java,I will not teach you the regular expression(If you are new to regular expression then please update yourself first via techcresendo.com)
In java we have java.util.regex package for regular expressions.This package basically contains three classes
  • Pattern:  This class represents the pattern in regular expression.Pattern is basically a format of text which needs to be matched in a group of texts.Patterns are constructed using regular expressions. e.g pattern
  • "[tT]rue" matches true or True

  • Matcher:  This class does the matching of the compiled pattern against an input string.

  • PatternSyntaxException: This class represents the exception which are thrown when your regular expression pattern is not correct.(It is unchecked exception)
Steps to create a pattern matching program:
  1. Create a pattern object.This object defines your regular expression.                                                                                                                           Pattern pattern=Pattern.compile(“regex”);

  2. Now with the help of Pattern object we can get Matcher object for a given input text(into which pattern to be  matched).                                                                                                                                                       Matcher matcher=pattern.matcher(INPUT_TEXT); 

  3. Now using this matcher object  we can easily find the pattern in the text as we will see in the example program.

package com.techy.rajeev;

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

public class PatternMatch {
  public static final String INPUT_TEXT = "This is a test for regular expression Testing.";
  public static final String PATTERN = "[tT]est";
  
  public static void main(String[] args) {
    Pattern pattern = Pattern.compile(PATTERN);
    Matcher matcher = pattern.matcher(INPUT_TEXT);
    while (matcher.find()) {
      System.out.print("Start pos: " + matcher.start());
      System.out.print(" End pos: " + matcher.end() + " ");
      System.out.println(matcher.group());
    }
  }
} 



Output:

Start pos: 10 End pos: 14 test
Start pos: 38 End pos: 42 Test
Read More ->>
DMCA.com Protected by Copyscape Online Plagiarism Tool