
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
Working with Matcher end() Method in Java Regular Expressions
The offset value after the last character is matched from the sequence according to the regex is returned by the method java.util.regex.Matcher.end(). This method requires no arguments. If no match occurs or if the match operation fails then the IllegalStateException is thrown.
A program that demonstrates the method Matcher.end() Java regular expressions is given as follows:
Example
import java.util.regex.Matcher; import java.util.regex.Pattern; public class Demo { public static void main(String args[]) { Pattern p = Pattern.compile("(a*b)"); Matcher m = p.matcher("caaabccaab"); System.out.println("The input string is: caaabccaab"); System.out.println("The Regex is: (a*b)"); System.out.println(); while (m.find()) { System.out.println("Index: " + m.end()); } } }
Output
The input string is: caaabccaab The Regex is: (a*b) Index: 5 Index: 10
Now let us understand the above program.
The subsequence “(a*b)” is searched in the string sequence "caaabccaab". The find() method is used to find if the subsequence is in the input sequence and the offset value after the last character is matched is printed using the end() method. A code snippet which demonstrates this is as follows:
Pattern p = Pattern.compile("(a*b)"); Matcher m = p.matcher("caaabccaab"); System.out.println("The input string is: caaabccaab"); System.out.println("The Regex is: (a*b)"); System.out.println(); while(m.find()) { System.out.println("Index: " + m.end()); }
Advertisements