Replace last occurrence of dash

A swapping-ground for Regular Expression syntax

Replace last occurrence of dash

Postby flopjoke » Sun Mar 08, 2020 2:54 am

I've googled a lot and also went through the PDF manual but can't seem to find the right way to do this.

I have many files with names in this format:
17_2020-02-16-130749.csv


What I'd like to do is replace the last occurrence of the dash with an underscore. The final result should be this:

17_2020-02-16_130749.csv


I've tried this: .*(-.*?) and that gives the group 1 as the last dash, but I don't know how to actually replace it with the underscore.

Any help is appreciated!
flopjoke
 
Posts: 2
Joined: Sun Mar 08, 2020 2:50 am

Re: Replace last occurrence of dash

Postby RegexNinja » Sun Mar 08, 2020 4:25 am

Hi,
The below regex caters to the format: 2Digits_4Digits-2Digits-2Digit-1OrMoreDigits, replacing the final - with an underscore.
If you have other name formats, please post.

#1 Regex Match/Replace:
^(\d{2}_\d{4}-\d{2}-\d{2})-(\d+)$
\1_\2


A much more generic, and dangerous regex would be:
(.*)-(.*)
\1_\2
It replaces the final - with an underscore in any filename (even filenames with only one -)
RegexNinja
 
Posts: 134
Joined: Fri Feb 21, 2020 5:26 pm

Re: Replace last occurrence of dash

Postby flopjoke » Sun Mar 08, 2020 5:28 am

Thank you! Both versions you posted work well.

Appreciate it :)
flopjoke
 
Posts: 2
Joined: Sun Mar 08, 2020 2:50 am

Re: Replace last occurrence of dash

Postby trm2 » Tue Mar 10, 2020 8:11 pm

Dangerous for those that do not know - simply means be very careful with your selections in the Content Pane. That is the only caveat.
Don't do a Ctrl-A to select all files and expect good results using a more 'universal' RegEx vs a more 'restrictive' RegEx, as I like to refer to them.

There are advantages to both. But sometimes restrictive is too restrictive and isn't flexible enough to handle every circumstance of file that you expected.
There are, however, many ways to write a RegEx usually and so universal does not have to mean match everything under the Sun just as restrictive doesn't have to
mean match only this one specific pattern.

But for those that do not heed this advice and wind up with a lot of garbage, take comfort in the Undo button. Volume II will hopefully help a lot of people learn with the
many examples of RegEx - most of which originate in these forums.
trm2
 
Posts: 155
Joined: Wed Jan 15, 2020 12:47 pm


Return to Regular Expressions