3

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:

  1. (?<!^baz)\.exe - using negative lookbehind, the matching group is only .exe part of the word
  2. ^(?!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
Alexander Samoylov
  • 1,290
  • 1
  • 15
  • 20
leontalbot
  • 2,423
  • 1
  • 19
  • 27
  • If you have tried anything please post it. –  Apr 01 '16 at 01:38
  • What have you tried? What exactly is going wrong? Do you get any errors? What are those errors? What have you tried to do to fix those errors? What happened when you did that? Remember to include these things when you make your question. Follow this guide to make sure your questions are of high quality: https://stackoverflow.com/help/how-to-ask – Matt C Apr 01 '16 at 02:14
  • 1
    The correct solution is `(? – Alexander Samoylov Apr 12 '21 at 12:05

2 Answers2

4

This would look behind for presence of baz and discard the match if it's present. I assume that you are checking filenames one by one. Hence used anchor ^ and $.

Regex: ^(?!baz).*\.exe$

Regex101 Demo

1

As @Wajahat noted, this question can be answered straight from Regex: match everything but (first google answer too).

^(?!.*(baz)).*exe

  • foo.exe : matches
  • baz.exe : does not match
  • whaterver.exe : matches
Community
  • 1
  • 1
KevinO
  • 4,111
  • 4
  • 23
  • 34