2014-09-29 65 views
0

我想用sed替換一個模式。我想進行全局搜索並替換 ,其中我將~~\d{3}~~替換爲A\d{3}\B。換句話說,我想 替換~~345~~A345B正則表達式 - 替換使用反向引用

我的文件(src.txt)包含一個行:

hello ~~123~~ hello ~~12~~ hello ~~456~~ hello

我想這個更改爲:

hello A123B hello ~~12~~ hello A456B hello

我想這在命令行上:

sed -i -c "s/~~(\d{3})~~/A\\1B/g" src.txt

然而,沒有什麼改變。我究竟做錯了什麼?

P.S. - 最終我想在Javascript中做這種替換 。

謝謝!

回答

0

在JS,這是很簡單的:

var string = 'hello ~~123~~ hello ~~12~~ hello ~~456~~ hello', 
    regex =/~~(\d{3})~~/g; 

string = string.replace(regex, 'A$1B'); 
console.log(string); // hello A123B hello ~~12~~ hello A456B hello 
+0

謝謝,山姆。我很好奇你將如何使用sed在命令行上執行此操作。有什麼想法嗎? – CurtisD 2014-09-29 20:00:01