regex

Nico Heid's picture

Regular Expression examples in Java

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.

  1. import java.util.regex.Matcher;
  2. import java.util.regex.Pattern;
  3.  
  4. public class RegexCoding {
  5.  
  6.         public static void main(String[] args) {
  7.  
  8.                 String source = "asdfdfdasdfdfdf";
  9.                 Pattern pattern = Pattern.compile("dfd");
  10.                 Matcher matcher = pattern.matcher(source);
  11.                 int hits = 0;
  12.                 while (matcher.find()) {
  13.                         hits++;
  14.                 }
  15.                 System.out.println(hits);
  16.  
  17.         }
  18. }

The result should be 2. So either our code is wrong, or the logic works differently than expected. And indeed, it does.Read more

Syndicate content