How do you show all the matches?For example I have one String “Hello world and how are you a”.
Here I have to get all the positions where letter ‘a’ resides.For that I wrote one sample java program. But here only start() and end() methods are available for matcher. How do I get the middle results? Please explain me..
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexTestStrings {
public static void main( String args[] ){
String line = "Hello world and how are you a";
String pattern = "[a]";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(line);
if (m.find( )) {
System.out.println(m.start());
System.out.println(m.end());
} else {
System.out.println("No result foud");
}
}
}
You can call
matcher.find()more than one time, and it will return the next occurence. So just replace yourifwith awhileand use some boolean flagmatchesFoundset totrueinside thewhileblock in order to be able to print the message if there was no match.