簡體   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