Regex help needed please.

Associate
Joined
17 Nov 2003
Posts
1,945
Location
Gateshead
I've turned my hand to a many, many things development related but regex continues to elude me!!

I need a regex to match filenames with extension where the filename part before the extension ends with a '-'.

Some example filenames...

filename.jpeg
filename-.png <-- MATCH
file name.doc
file name 3.mp4
file name -.dxg <-- MATCH
file.name.mov

NOTE: The filename may contain any valid character including periods.

Many thanks in advance :)
 
Depending on your development environment you could also just get the filename with the extension removed and test whether the last character is a hyphen, e.g. for c#

if(Path.GetFilenameWithoutExtension(filename).Last() == '-')
//do something

Regex is probably cleaner, but may be cumbersome to cover all edge cases, especially if the filename may also contain periods
 
regex101 is a great resource for learning about regex's. Once it all clicks in your mind it's really straightforward... just looks daunting to begin with :D
 
I've turned my hand to a many, many things development related but regex continues to elude me!!

I need a regex to match filenames with extension where the filename part before the extension ends with a '-'.

Some example filenames...

filename.jpeg
filename-.png <-- MATCH
file name.doc
file name 3.mp4
file name -.dxg <-- MATCH
file.name.mov

NOTE: The filename may contain any valid character including periods.

Many thanks in advance :)


This does what you want. (Python)

Code:
import re

tests = ["filename.jpeg",
        "filename-.png", # <-- MATCH
        "file name.doc",
        "file name 3.mp4",
        "file name -.dxg", #  <-- MATCH
        "file.name.mov"]

pattern = r"(-\.[a-zA-Z]{3,4}$)"

for test in tests:
    match = re.search(pattern, test)
    if match:
        print(f"{test} : Matched: {match.groups()[0]}")

Output:
Code:
filename-.png : Matched: -.png
file name -.dxg : Matched: -.dxg
 
Flippy's suggestion help me out. I needed the pure regex, it's for some software that requires a regex input.
I agree there are many ways to skin a cat (c#, python, JS, etc) but I needed a specific way in this case.

Thanks all! :)
 
Back
Top Bottom