kritop
kritop

Reputation: 607

regex with condition to replace "-" or "_" before the file extension with a dot

examples:

this-is_a-random-filenam-jpg
this-is_a-random-filenam-png
this-is_a-random-filenam-gif
this-is_a-random-filenam-pdf

needed result:

this-is_a-random-filenam.jpg
this-is_a-random-filenam.png
this-is_a-random-filenam.gif
this-is_a-random-filenam.pdf

I came up with

\-(?=[^-]*$)

it just marks the last occurrence, doesn't check the condition that there is an actual valid file extension after it (jpeg,jpg,pdf,gif in my case) and doesn't work with "_".

Upvotes: 1

Views: 56

Answers (2)

Niitaku
Niitaku

Reputation: 835

Expression

To perform this change by taking care of file extension, you can use this regex:

(-|_)(?=(?:jpe?g|png|gif|pdf)$)

And replace the matches with a ..

You will have to list all file extensions you want in this pattern.

See the regex demo

PHP example

$re = '/(-|_)(?=(?:jpe?g|png|gif|pdf)$)/';
$str = 'this-is_a-random-filenam-jpg
this-is_a-random-filenam-png
this-is_a-random-filenam-gif
this-is_a-random-filenam-pdf';
$subst = '.';

$result = preg_replace($re, $subst, $str);

Upvotes: 1

Sandip Patel
Sandip Patel

Reputation: 176

use following flags at the end of your regular expression

/(-|_)(?=jpg|png|gif|pdf)/gm

Upvotes: 0

Related Questions