2014-06-25 93 views
0

我可以這樣做嗎?正則表達式替換字不以某些符號開頭

...blah-blah...AA_word.......blah-blah...AB_word......word........Nword.... 

我需要更換隻字不以「AB_」開始的那些OCCURENCES所以它看起來就像這樣:

...blah-blah...AA_XXXX.......blah-blah...AB_word......XXXX........NXXXX.... 

這可能嗎?我對或多或少熟悉正則表達式,但仍然無法知道如何去做。編程語言並不重要 - PHP,JS或C#,無論

回答

3

搜索:XXXX

一個Perl:(?<!AB_)word
,代之以實施:

my $str = "...blah-blah...AA_word.......blah-blah...AB_word......word........Nword...."; 
$str =~ s/(?<!AB_)word/XXXX/g; 
say $str; 

輸出:

...blah-blah...AA_XXXX.......blah-blah...AB_word......XXXX........NXXXX.... 

用PHP:

$str = "...blah-blah...AA_word.......blah-blah...AB_word......word........Nword...."; 
$str = preg_replace('/(?<!AB_)word/', 'XXXX', $str); 
echo "$str\n"; 
+0

的感謝!像一個魅力工作 – phantasm

+1

從來不知道這一點。對於好奇的貓,這被稱爲*消極後視斷言*。感謝 –

+0

+1瞭解需求權。 – anubhava

0

在JS:

var s = "...blah-blah...AA_word.......blah-blah...AB_word......word........Nword...." 

s.replace("AB_word", "????").replace(/word/g, "XXXX").replace("????", "AB_word") 
// results in 
// ...blah-blah...AA_XXXX.......blah-blah...AB_word......XXXX........NXXXX.... 

HTH