簡體   English   中英

正則表達式從字符串中刪除字符串

[英]Regex to remove string from string

想知道我是否可以在下面編寫正則表達式,目前正在使用 String.Remove(17,7)

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

我想從上面的字符串中刪除 .zip.ytu

只需使用String.Replace()

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

完全匹配不需要正則表達式。

這是 OP 要求使用正則表達式的答案。

要使用正則表達式,請將替換文本放入匹配項( ) ,然后將該匹配項替換為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
txt = txt.Replace(".zip.ytu", "");

你為什么不簡單地做上面的?

真的不知道“.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());

使用字符串。替換:

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

這是我用於更復雜重復的方法。 查看鏈接: 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);                             

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM