Regular expressions perform less well the longer and more complicated that they get. For something like this, it should be better performing and easier to understand to match the input against three regular expressions.
String match = "quxfoobar";
Pattern start = Pattern.compile("^foo");
Pattern contain = Pattern.compile("\\/foo");
Pattern end = Pattern.compile("bar$");
boolean m = (
!start.matcher(match).find() &&
!contain.matcher(match).find() &&
end.matcher(match).find()
);
Edit: since there is some question as to whether three regex would be faster in this case, I wrote a benchmark. When I run it, the single regular expression (taken from another answer) is three times as slow as running with three separate regular expressions.
import java.util.regex.*;
import java.util.*;
public class Test {
private static final Pattern START = Pattern.compile("^foo");
private static final Pattern CONTAIN = Pattern.compile("\\/foo");
private static final Pattern END = Pattern.compile("bar$");
private static final Pattern ONEPATTERN = Pattern.compile("^(?!foo)(\\/(?!foo)|[^\\/])*bar$");
public static void main(String[] args){
String[] in = createInput();
timeOnePattern(in);
timeThreePatterns(in);
System.exit(0);
}
public static String[] createInput(){
String[] words = {"foo","bar","baz","biz","/foo"};
Random rand = new Random();
String[] in = new String[10000];
for (int i=0; i<in.length; i++){
StringBuilder sb = new StringBuilder();
for (int j=0; j<4; j++){
sb.append(words[rand.nextInt(words.length)]);
}
in[i] = sb.toString();
}
return in;
}
public static void timeThreePatterns(String[] in){
long startTime = System.nanoTime();
for (String s: in){
boolean b = (!START.matcher(s).find() && !CONTAIN.matcher(s).find() && END.matcher(s).find());
}
long endTime = System.nanoTime();
System.out.println("Three regular expressionv took " + (endTime - startTime) + " nanoseconds.");
}
public static void timeOnePattern(String[] in){
long startTime = System.nanoTime();
for (String s: in){
ONEPATTERN.matcher(s).matches();
}
long endTime = System.nanoTime();
System.out.println("Single regular expression took " + (endTime - startTime) + " nanoseconds.");
}
}