1

I have the following regex:

^((?!.*/gradle-wrapper\.jar$)|(.*\.jar$)|(.*\.exe$))

and the following data:

rupe-engine/src/main/groovy/com/rupe/engine/JongoAutoConfiguration.java

gradle/wrapper/gradle-wrapper.jar

gradle/wrapper/gradle-bundle.exe

gradle/wrapexe/gradle.git

testit.jar

Expected result:

Match gradle/wrapper/gradle-bundle.exe and testit.jar.

Actual result:

Also matching gradle/wrapper/gradle-wrapper.jar, despite me trying to "black-list" this filename.

Tom Lord
  • 22,829
  • 4
  • 43
  • 67
scphantm
  • 3,491
  • 6
  • 34
  • 70
  • What is the logic you want to implement? What's your data? Is it a big string or an array of strings? – Eric Duminil May 09 '17 at 16:20
  • @scphantm I have tried to re-word your title/question to make it more understandable. Please review my changes, and re-edit if necessary. In future, please see [how to ask](https://stackoverflow.com/help/how-to-ask) for a summary on what makes a good question. – Tom Lord May 09 '17 at 16:25

1 Answers1

0

Your regex is "malfunctioning" because you use a lookahead as an alternative branch, and it is thus not restricting the pattern any longer.

You seem to want to match strings that end with .jar or .exe and that do not end with /gradle-wrapper.jar. Use

^(?!.*/gradle-wrapper\.jar$).*\.(?:jar|exe)$

See the regex demo

Details:

  • ^ - start of a string
  • (?!.*/gradle-wrapper\.jar$) - fail the match if after any 0+ chars (.*) there is /gradle-wrapper.jar substring immediately followed with the end of string ($)
  • .*\. - match any 0+ chars (well, other than line break chars) up to the last .
  • (?:jar|exe) - either jar or exe
  • $ - end of string.
Wiktor Stribiżew
  • 484,719
  • 26
  • 302
  • 397
  • Damn, i was close. Thank you so much. In another 20 years i may figure out regex. – scphantm May 09 '17 at 16:20
  • @scphantm: If you have not done that yet, do all lessons at [regexone.com](http://regexone.com/), read through [regular-expressions.info](http://www.regular-expressions.info), [regex SO tag description](http://stackoverflow.com/tags/regex/info) (with many other links to great online resources), and the community SO post called [What does the regex mean](http://stackoverflow.com/questions/22937618/reference-what-does-this-regex-mean). A [rexegg.com](http://rexegg.com) is also a great site, you may learn a lot about how lookarounds work there. – Wiktor Stribiżew May 09 '17 at 16:23
  • @scphantm: If the answer turned out helpful to you, please consider also upvoting. – Wiktor Stribiżew May 11 '17 at 06:23