When I first had to use regular expressions in Java I made some fairly common mistakes.
Let's start out with a simple search.
simple string matching
We want to search the string: asdfdfdasdfdfdf for occurences of dfd. I can find it four times in the String.
Let's evaluate what our little Java program says.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexCoding {
public static void main(String[] args) {
String source = "asdfdfdasdfdfdf";
Pattern pattern = Pattern.compile("dfd");
Matcher matcher = pattern.matcher(source);
int hits = 0;
while (matcher.find()) {
hits++;
}
System.out.println(hits);
}
}
The result should be 2. So either our code is wrong, or the logic works differently than expected. And indeed, it does.Read more