Mega Code Archive

 
Categories / Java Tutorial / Regular Expressions
 

A negative behind ahead

import java.util.regex.Matcher; import java.util.regex.Pattern; public class NegativeLookBehindExample {   public static void main(String args[]) throws Exception {     String regex = "(and)";     Pattern pattern = Pattern.compile(regex);     String candidate = "candidate";     Matcher matcher = pattern.matcher(candidate);     String msg = "";     int counter = 0;     String tmp = null;     while (matcher.find()) {       int start = matcher.start();       int end = matcher.end();       tmp = ":" + matcher.group() + ":";       msg += tmp;       System.out.println("counter = " + counter);       counter++;       System.out.println("start = " + start);       System.out.println("end = " + end);       System.out.println("tmp = " + tmp);       System.out.println("candidate.length() = " + candidate.length() + "\n");     }   } } /**/ counter = 0 start = 1 end = 4 tmp = :and: candidate.length() = 9