繁体   English   中英

正则表达式替换一个字符的所有出现?

[英]regex replace all occurances of one character?

关于这一点有很多主题,但是我想不通,寻找一些技巧,应该不会那么困难。

我有文件名:

test_file_from_mpc.mp4_snapshot_13.29_[2015.05.13_21.10.11].jpg

我正在尝试使用正则表达式替换字符_,然后从快照开始的所有内容

我得到了快照,但是我似乎无法了解如何捕获要选择的_的所有情况

(_)(snapshot)(.*)

仅选择1 _

我读过。 应该选择“任何单个字符”,不确定如何正确使用它,或者这是否是我在寻找的东西。

任何指导都会很棒! (这可能是100%的欺骗,但是我已经检查了所有建议的线程,而没有找到针对此看似简单的问题的解决方案!)

尚无法评论,但要使正则表达式匹配多个匹配项,您需要使用g-全局修饰符。

/(_snapshot.*$|_|\.)/gi

https://regex101.com/r/aI7fF8/2

如果仅用空格替换所有匹配的出现,请记住修剪最后一个空格。

这也是一个php示例

<?php
$str = "test_file_from_mpc.mp4_snapshot_13.29_[2015.05.13_21.10.11].jpg";
$res = preg_replace(array("/_snapshot.*$/", "/[_.]/"), array("", " "), $str);
print $res; // test file from mpc mp4
snapshot.*$|[_.]

您可以尝试此操作。按space替换。请参见演示。

https://regex101.com/r/mT0iE7/13

$re = "/snapshot.*$|[_.]/im"; 
$str = "test_file_from_mpc.mp4_snapshot_13.29_[2015.05.13_21.10.11].jpg"; 
$subst = " "; 

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

另一种(可能更快,但不是更漂亮)的方法是使用explode()和implode()。

// Split string by underscores
$pieces = explode('_', $filename);

// Get the number of pieces
$n = count($pieces);

// Keep just the file extension in the last piece
$pieces[$n] = substr($pieces[$n], strpos($pieces[$n], '.'));

// Remove the other unwanted pieces
unset($pieces[$n - 1];
unset($pieces[$n - 2];

// Reassemble with spaces instead of underscores
$new_string = implode(' ', $pieces);

暂无
暂无

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

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