Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
MatchResult start() method in Java with examples.
The java.util.regex.MatcheResult interface provides methods to retrieve the results of a match.
You can get an object of this interface using the toMatchResult() method of the Matcher class. This method returns a MatchResult object which represents the match state of the current matcher.
The start() method of this interface returns the beginning index of the current match.
Example
import java.util.Scanner;
import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StartExample {
public static void main(String args[]) {
//Reading String from user
System.out.println("Enter a String");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
String regex = "\W";
//Compiling the regular expression
Pattern pattern = Pattern.compile(regex);
//Retrieving the matcher object
Matcher matcher = pattern.matcher(input);
if(matcher.find()) {
System.out.println("Match occurred");
}else {
System.out.println("Match not occurred");
}
//Retrieving the MatchResult object
MatchResult res = matcher.toMatchResult();
int start = res.start();
System.out.println(start);
}
}
Output
Enter a String This * is # sample % text with & non word characters Match occurred 4
Advertisements