Finding start and end index of string using Regular expression

Ads
 

Finding start and end index of string using Regular expression

This Example describes the way for finding start and end index of the string using regular expression. For this we are going to make program named Finding_index.java.

This Example describes the way for finding start and end index of the string using regular expression. For this we are going to make program named Finding_index.java.

Finding start and end index of string using Regular expression

     

This Example describes the way for finding start and end index of the string using regular expression. For this we are going to make program named Finding_index.java. The steps involved in program  Finding_index.java are described below:-

String[] text = {"Russian military convoy passed through Russian" + " Mountains in Russian Ossetia"}:-Declaring text from where the index of the particular word "Russian" will be retrieve.

String regex="R\\w*":-This is the expression to search words starting with letter "R".

Pattern p = Pattern.compile(regex):-Creating a pattern object and compiling  the given regular expression into a pattern.

(matcher.find()):-This is the method of matcher class which is generally used for finding the next subsequence of the input sequence, it usually returns a boolean value.

matcher.start():-This method is used for finding the start index of the word starting with letter R.

matcher.end():-This method is used for finding the end index of the word starting with letter R.

Finding_index.java

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

public class Finding_index {

  public static void main(String[] args) {
  String[] text = {"Russian military convoy 
  passed through Russian" 
+
  " Mountains in Russian Ossetia"};
 String regex="R\\w*";
  Pattern p = Pattern.compile(regex);

  for (int i = 0; i < text.length; i++) {
  System.out.println("Text is : " + text[i]);
 System.out.println("========================");
  Matcher matcher = p.matcher(text[i]);

  while (matcher.find()) {
  System.out.println("Starting & ending 
  index of" 
+ matcher.group()":=" +
 "start=" + matcher.start() " end = " + matcher.end());
  }
  
  if (matcher.matches()) {
  System.out.println("m1.matches() start = " +
  matcher.start() " end = " + matcher.end());
  }
 System.out.println("========================");
  }
  }
}

Output of the program:-

Text is : Russian military convoy passed through Russian Mountains in Russian Ossetia
========================
Starting & ending index ofRussian:=start=0 end = 7
Starting & ending index ofRussian:=start=39 end = 46
Starting & ending index ofRussian:=start=60 end = 67
========================


Download Source Code

Ads

Ads