Fabio Costa
Fabio Costa

Reputation: 53

Regex match anything except ending string

I'm trying to make a regex that matches anything except an exact ending string, in this case, the extension '.exe'.

Examples for a file named:

  1. 'foo' (no extension) I want to get 'foo'
  2. 'foo.bar' I want to get 'foo.bar'
  3. 'foo.exe.bar' I want to get 'foo.exe.bar'
  4. 'foo.exe1' I want to get 'foo.exe1'
  5. 'foo.bar.exe' I want to get 'foo.bar'
  6. 'foo.exe' I want to get 'foo'

So far I created the regex /.*\.(?!exe$)[^.]*/ but it doesn't work for cases 1 and 6.

Upvotes: 4

Views: 3449

Answers (4)

Alexe Barlescu
Alexe Barlescu

Reputation: 397

string pattern = @" (?x)  (.* (?= \.exe$ )) | ((?=.*\.exe).*)";
  • First match is a positive look-ahead that checks if your string ends with .exe. The condition is not included in the match.
  • Second match is a positive look-ahead with the condition included in the match. It only checks if you have something followed by .exe.

(?x) is means that white spaces inside the pattern string are ignored. Or don't use (?x) and just delete all white spaces.

It works for all the 6 scenarios provided.

Upvotes: -1

bobble bubble
bobble bubble

Reputation: 18490

You can use a positive lookahead.

^.+?(?=\.exe$|$)
  • ^ start of string
  • .+? non greedily match one or more characters...
  • (?=\.exe$|$) until literal .exe occurs at end. If not, match end.

See demo at Rubular.com

Upvotes: 2

user3089519
user3089519

Reputation:

Do you mean regex matching or capturing?

There may be a regex only answer, but it currently eludes me. Based on your test data and what you want to match, doing something like the following would cover both what you want to match and capture:

name = 'foo.bar.exe'
match = /(.*).exe$/.match(name)
if match == nil
  # then this filename matches your conditions 
  print name
else
  # otherwise match[1] is the capture - filename without .exe extension
  print match[1]
end

Upvotes: 0

sawa
sawa

Reputation: 168081

Wouldn't a simple replacement work?

string.sub(/\.exe\z/, "")

Upvotes: 2

Related Questions