- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Determining the position and length of the match Java regex
The start() method of the java.util.regex.Matcher class returns the starting position of the match (if a match occurred).
Similarly, the end() method of the Matcher class returns the ending position of the match.
Therefore, return value of the start() method will be the starting position of the match and the difference between the return values of the end() and start() methods will be the length of the match.
Example
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class MatcherExample { public static void main(String[] args) { int start = 0, len = -1; Scanner sc = new Scanner(System.in); System.out.println("Enter input text: "); String input = sc.nextLine(); String regex = "\d+"; //Creating a pattern object Pattern pattern = Pattern.compile(regex); //Matching the compiled pattern in the String Matcher matcher = pattern.matcher(input); while (matcher.find()) { start = matcher.start(); len = matcher.end()-start; } System.out.println("Position of the match : "+start); System.out.println("Length of the match : "+len); } }
Output
Enter input text: sample data with digits 12345 Position of the match : 24 Length of the match : 5
Advertisements
To Continue Learning Please Login
Login with Google