English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
java.util.regex.Matcher class represents an engine for executing various matching operations. This class has no constructor and can be used withmatches()
created by the method of java.util.regex.Pattern class/Get the object of this class.
The method of Matcher classstart()The method returns the starting index of the matched character.
Example
subexpression "[...]" to match the specified characters within the curly braces in the input string. In the following example, use this expression to match the character 't'. Here,
We have used thecompile()
The method compiles the regular expression.
Get Matcher object.
matcher()
Call this method on each match item.
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class StartExample { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter input text:"); String input = sc.nextLine(); String regex = "[t]"; //Create a pattern object Pattern pattern = Pattern.compile(regex); //Match the compiled pattern in the string Matcher matcher = pattern.matcher(input); int count = 0; while (matcher.find()) { int start = matcher.start(); System.out.println(start); } } }
Output Result
Enter input text: Hello, how are you? Welcome to w3codebox 26 31 42
Since the character 't' appears three times in the input string, you can observe three index values (representing the index of each character).