From the following list
"foo.exe"
"foo.dmg"
"baz.exe"
"this-is-another-file-name.exe"
...
what java regex would match every strings that end with ".exe"
except a specific string "baz.exe"
Thanks!
EDIT: I've tried (?=\.exe$)(?!baz\.exe)
UPDATE by user. There are two solutions:
(?<!^baz)\.exe
- using negative lookbehind, the matching group is only .exe part of the word^(?!baz\.exe).*
- using negative lookahead, the matching group contain the whole file name
Both work with "grep -P" and from Java (\\
must be replace with \
).
Be aware also that Java's Matcher.matches() and Matcher.find() work differently, see my example:
import java.util.regex.*;
public class RegexLookaround {
public static void main(String args[]) {
String[] strings = new String[] { "bax.exe", "baz.exe", "baza.exe", "abaz.exe", "bazbaz.exe" };
Pattern p = Pattern.compile(args[0]);
for (String s : strings) {
Matcher m = p.matcher(s);
if (m.matches()) {
System.out.println("m: " + m.group());
}
while (m.find()) {
System.out.println("f: " + m.group());
}
}
}
}
Test:
$ java -cp . RegexLookaround '(?<!^baz)\.exe'
f: .exe
f: .exe
f: .exe
f: .exe
$ java -cp . RegexLookaround '^(?!baz\.exe).*'
m: bax.exe
m: baza.exe
m: abaz.exe
m: bazbaz.exe