2012-01-01 231 views
8
我一直在努力的實際努力理解正則表達式之間

, 有什麼辦法,我可以代替字符(S),即兩個字符串/ 例如 我有正則表達式替換

sometextREPLACEsomeothertext

之間

我想更換,更換(可在實際工作中的任何東西)sometext和someothertext之間僅有與其他字符串。 任何人都可以請幫助我這個。

編輯 想,我的輸入字符串爲

sometext_REPLACE_someotherText_something_REPLACE_nothing

我要替換導致sometext和someotherText 之間的替換文本輸出如下

sometext_THISISREPLACED_some otherText_something_REPLACE_nothing

謝謝

+0

爲什麼你認爲正則表達式是正確的工具? – Oded 2012-01-01 08:22:53

+1

''sometextREPLACEsomeothertext「.Replace(」REPLACE「,」OtherText「)' – Matthias 2012-01-01 08:23:53

+0

@MatthiasKoch它不會,它會替換所有不需要的REPLACE文本,例如,如果我有sometext_REPLACE_someotherText_one_REPLACE_two,它會替換所有的替換文本。 – 41K 2012-01-01 08:27:58

回答

8

如果我正確理解你的問題,你可能想使用lookahead and lookbehind你的正則表達式

(?<=...) # matches a positive look behind 
(?=...) # matches a positive look ahead 

因此

(?<=sometext)(\w+?)(?=someothertext) 

將匹配任何「字」與下面的「sometext」和隨後「someothertext」

在C#中至少1個字符:

result = Regex.Replace(subject, @"(?<=sometext)(\w+?)(?=someothertext)", "REPLACE"); 
+0

是的,這非常接近,但它仍然看起來像貪婪的匹配,你可以讓它變成懶惰的。 – 41K 2012-01-01 09:46:47

+2

@ 41K:編輯後的正則表達式很懶。 – 2012-01-01 09:50:40

+0

非常好。謝謝。 – 41K 2012-01-01 09:52:05

0

這是測試如果字符串是有效的正則表達式。

\^.REPLACE.\ 

C#替換

string s = "sdfsdfREPLACEdhfsdg"; 
string v = s.Replace("REPLACE", "SOMETEXT"); 
+0

它不起作用,請參閱頂部的我的評論 – 41K 2012-01-01 08:30:44

+0

難道你不能只是去s.Replace(「sometext_REPLACE_other text」,「sometext_TEXT_othertext」)? – 2012-01-01 08:39:31

+0

不可以,因爲REPLACE可以是源字符串中的任何東西 – 41K 2012-01-01 08:45:46