简体   繁体   English

带有条件的正则表达式在文件扩展名之前用点替换“-”或“_”

[英]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 "_".它只是标记最后一次出现,不检查它后面是否存在实际有效文件扩展名的条件(在我的情况下为 jpeg、jpg、pdf、gif)并且不适用于“_”。

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 PHP 示例

$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);

在正则表达式的末尾使用以下标志

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM