2011-12-27 241 views
4

去除串想,如果我可以寫正則表達式來做到以下,目前使用String.Remove(17,7)正則表達式從字符串

string txt = "werfds_tyer.abc.zip.ytu_20111223170226_20111222.20111222"; 

我想從上面的字符串

回答

9
刪除.zip.ytu

只需使用String.Replace()

String.Replace(".zip.ytu", ""); 

你並不需要精確匹配正則表達式。

+0

LOL ...簡單的岩石:) – user570715 2011-12-27 19:17:17

3
txt = txt.Replace(".zip.ytu", ""); 

你爲什麼不簡單地在上面做?

2

使用與string.replace:

txt = txt.Replace(".zip.ytu", ""); 
4

下面是使用正則表達式的任擇議定書要求的答案。 ;-)

要使用正則表達式,把replacment文本匹配(),然後替換匹配任何內容(的String.Empty):

string text = @"werfds_tyer.abc.zip.ytu_20111223170226_20111222.20111222"; 
string pattern = @"(\.zip\.ytu)"; 

Console.WriteLine(Regex.Replace(text, pattern, string.Empty)); 

// Outputs 
// werfds_tyer.abc_20111223170226_20111222.20111222 

HTH

2

真的不知道什麼是「.zip.ytu」,但如果你並不需要精確匹配,你可能會使用類似的東西:

string txt = "werfds_tyer.abc.zip.ytu_20111223170226_20111222.20111222"; 

Regex mRegex = new Regex(@"^([^.]*\.[^.]*)\.[^.]*\.[^_]*(_.*)$"); 
Match mMatch = mRegex.Match(txt); 

string new_txt = mRegex.Replace(txt, mMatch.Groups[1].ToString() + mMatch.Groups[2].ToString()); 
+0

[^。] *(零到無限)不是一段時間。爲什麼用'*'殺死正則表達式解析器,特別是零條件有效?相反,對許多人使用「+」表示-1-會提供更好的提示,而不會導致回溯。你真的相信隨着時間的推移,什麼也沒有;或者你認爲至少有一個角色會存在?如果你相信1個字符將存在,那麼使用它而不是*。 HTH – OmegaMan 2011-12-28 01:44:39

+0

我寫道,我不知道什麼是「.zip.ytu」,而且,我不知道整個字符串是什麼。所以,我可以承認這個字符串可能類似「..test1.test2_123123.123123」,因爲爲什麼不呢?如果我真的知道這些點之間總會有東西,那麼當然,我會用「+」而不是「*」。怎麼了? – 2011-12-28 04:34:54

0

這裏是我使用更復雜的repaces的方法。查看鏈接:http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.replace(v=vs.110).aspx正則表達式替換。我還添加了下面的代碼。

string input = "This is text with far too much " + 
       "whitespace."; 
    string pattern = "\\s+"; 
    string replacement = " "; 
    Regex rgx = new Regex(pattern); 
    string result = rgx.Replace(input, replacement); 

    Console.WriteLine("Original String: {0}", input); 
    Console.WriteLine("Replacement String: {0}", result);