In the following example:
class ZiggyTest2{
public static void main(String[] args){
Pattern p = Pattern.compile("Water water WATER everywhere");
Matcher m = p.matcher("water");
while(m.find()){
System.out.println(m.start() + " " + m.group());
}
System.out.println("[Done]");
}
}
The m.find() method is always false so it is not finding the string "water". What is the reason for this?
You have inverted the strings:
Pattern
compiles the regex,Matcher
applies on an input.You should have:
Pattern p = Pattern.compile("water");
Matcher m = p.matcher("Water water WATER everywhere");
Also note that if you want case insensitive matching, you want to initialize your pattern with either of:
Pattern p = Pattern.compile("water", Pattern.CASE_INSENSITIVE);
// or:
Pattern p = Pattern.compile("(?i)water");